!function(e){"use strict";function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}sm.siteId=sm.conf.engagement.site_id;var n=t(e);function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function i(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0&&"[object Array]"===Object.prototype.toString.call(e)},w=Number.isInteger||function(e){return e<<0===e},E=function(e){return"[object Number]"===Object.prototype.toString.call(e)},O=function(e){return"[object Object]"===Object.prototype.toString.call(e)},S=function(e){return null!=e&&"object"===o(e)&&!0===e["@@functional/placeholder"]},T=function(e){return"[object String]"===Object.prototype.toString.call(e)},k=function(e){return"function"==typeof e["@@transducer/step"]},x=function(e,t){for(var n=0,r=t.length,i=Array(r);n=arguments.length)?c=n[a]:(c=arguments[o],o+=1),i[a]=c,S(c)||(s-=1),a+=1}return s<=0?r.apply(this,i):l(s,e(t,i,r))}},F=function(e,t,n){return function(){var r=arguments.length;if(0===r)return n();var i=arguments[r-1];if(!_(i)){var o=R(arguments,0,r-1);if("function"==typeof i[e])return i[e].apply(i,o);if(k(i)){var s=t.apply(null,o);return s(i)}}return n.apply(this,arguments)}},B=function(){function e(e,t){this.xf=t,this.f=e,this.all=!0}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.all&&(e=this.xf["@@transducer/step"](e,!0)),this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){return this.f(t)||(this.all=!1,e=C(this.xf["@@transducer/step"](e,!1))),e},U((function(t,n){return new e(t,n)}))}(),H=function(){function e(e,t){this.xf=t,this.f=e,this.any=!1}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.any||(e=this.xf["@@transducer/step"](e,!1)),this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){return this.f(t)&&(this.any=!0,e=C(this.xf["@@transducer/step"](e,!0))),e},U((function(t,n){return new e(t,n)}))}(),W=function(){function e(e,t){this.xf=t,this.pos=0,this.full=!1,this.acc=new Array(e)}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.acc=null,this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){return this.store(t),this.full?this.xf["@@transducer/step"](e,this.getCopy()):e},e.prototype.store=function(e){this.acc[this.pos]=e,this.pos+=1,this.pos===this.acc.length&&(this.pos=0,this.full=!0)},e.prototype.getCopy=function(){return d(R(this.acc,this.pos),R(this.acc,0,this.pos))},U((function(t,n){return new e(t,n)}))}(),G=function(){function e(e,t){this.xf=t,this.n=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=M.result,e.prototype["@@transducer/step"]=function(e,t){return this.n>0?(this.n-=1,e):this.xf["@@transducer/step"](e,t)},U((function(t,n){return new e(t,n)}))}(),z=function(){function e(e,t){this.xf=t,this.pos=0,this.full=!1,this.acc=new Array(e)}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.acc=null,this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){return this.full&&(e=this.xf["@@transducer/step"](e,this.acc[this.pos])),this.store(t),e},e.prototype.store=function(e){this.acc[this.pos]=e,this.pos+=1,this.pos===this.acc.length&&(this.pos=0,this.full=!0)},U((function(t,n){return new e(t,n)}))}(),J=function(){function e(e,t){this.xf=t,this.pred=e,this.lastValue=void 0,this.seenFirstValue=!1}return e.prototype["@@transducer/init"]=function(){return this.xf["@@transducer/init"]()},e.prototype["@@transducer/result"]=function(e){return this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){var n=!1;return this.seenFirstValue?this.pred(this.lastValue,t)&&(n=!0):this.seenFirstValue=!0,this.lastValue=t,n?e:this.xf["@@transducer/step"](e,t)},U((function(t,n){return new e(t,n)}))}(),Q=function(){function e(e,t){this.xf=t,this.f=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=M.result,e.prototype["@@transducer/step"]=function(e,t){if(this.f){if(this.f(t))return e;this.f=null}return this.xf["@@transducer/step"](e,t)},U((function(t,n){return new e(t,n)}))}(),Y=function(){function e(e,t){this.xf=t,this.f=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=M.result,e.prototype["@@transducer/step"]=function(e,t){return this.f(t)?this.xf["@@transducer/step"](e,t):e},U((function(t,n){return new e(t,n)}))}(),K=function(){function e(e,t){this.xf=t,this.f=e,this.found=!1}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.found||(e=this.xf["@@transducer/step"](e,void 0)),this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){return this.f(t)&&(this.found=!0,e=C(this.xf["@@transducer/step"](e,t))),e},U((function(t,n){return new e(t,n)}))}(),X=function(){function e(e,t){this.xf=t,this.f=e,this.idx=-1,this.found=!1}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.found||(e=this.xf["@@transducer/step"](e,-1)),this.xf["@@transducer/result"](e)},e.prototype["@@transducer/step"]=function(e,t){return this.idx+=1,this.f(t)&&(this.found=!0,e=C(this.xf["@@transducer/step"](e,this.idx))),e},U((function(t,n){return new e(t,n)}))}(),$=function(){function e(e,t){this.xf=t,this.f=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.xf["@@transducer/result"](this.xf["@@transducer/step"](e,this.last))},e.prototype["@@transducer/step"]=function(e,t){return this.f(t)&&(this.last=t),e},U((function(t,n){return new e(t,n)}))}(),Z=function(){function e(e,t){this.xf=t,this.f=e,this.idx=-1,this.lastIdx=-1}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=function(e){return this.xf["@@transducer/result"](this.xf["@@transducer/step"](e,this.lastIdx))},e.prototype["@@transducer/step"]=function(e,t){return this.idx+=1,this.f(t)&&(this.lastIdx=this.idx),e},U((function(t,n){return new e(t,n)}))}(),ee=function(){function e(e,t){this.xf=t,this.f=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=M.result,e.prototype["@@transducer/step"]=function(e,t){return this.xf["@@transducer/step"](e,this.f(t))},U((function(t,n){return new e(t,n)}))}(),te=function(){function e(e,t){this.xf=t,this.n=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=M.result,e.prototype["@@transducer/step"]=function(e,t){return 0===this.n?C(e):(this.n-=1,this.xf["@@transducer/step"](e,t))},U((function(t,n){return new e(t,n)}))}(),ne=function(){function e(e,t){this.xf=t,this.f=e}return e.prototype["@@transducer/init"]=M.init,e.prototype["@@transducer/result"]=M.result,e.prototype["@@transducer/step"]=function(e,t){return this.f(t)?this.xf["@@transducer/step"](e,t):C(e)},U((function(t,n){return new e(t,n)}))}(),re=U((function(e,t){return e+t})),ie=D((function(e,t,n){if(t>=n.length||t<-n.length)return n;var r=(t<0?n.length:0)+t,i=d(n);return i[r]=e(n[r]),i})),oe=U(F("all",B,(function(e,t){for(var n=0;n=0?r:0);n=0;){if(e(t[n]))return t[n];n-=1}}))),Pe=U(F("findLastIndex",Z,(function(e,t){for(var n=t.length-1;n>=0;){if(e(t[n]))return n;n-=1}return-1}))),Me=U(L("forEach",(function(e,t){for(var n=t.length,r=0;rt})),qe=U((function(e,t){return e>=t})),Ue=U(m),De=U((function(e,t){return e in t})),Ve=U((function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t})),Fe=q(y),Be=D((function(e,t,n){return ge(Math.max(e.length,t.length,n.length),(function(){return e.apply(this,arguments)?t.apply(this,arguments):n.apply(this,arguments)}))})),He=re(1),We=D((function(e,t,n){e=e=0?e:n.length;var r=R(n);return r.splice(e,0,t),r})),Ge=D((function(e,t,n){return e=e=0?e:n.length,d(d(R(n,0,e),t),R(n,e))})),ze=U(L("intersperse",(function(e,t){for(var n=[],r=0,i=t.length;r0&&(e.hasOwnProperty(0)&&e.hasOwnProperty(e.length-1)))))})),Ye=q((function(e){return null==e})),Ke=function(){var e=!{toString:null}.propertyIsEnumerable("toString"),t=["constructor","valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],n=function(){return arguments.propertyIsEnumerable("length")}(),r=function(e,t){for(var n=0;n=0;)m(o=t[s],i)&&!r(a,o)&&(a[a.length]=o),s-=1;return a})):q((function(e){return Object(e)!==e?[]:Object.keys(e)}))}(),Xe=q((function(e){var t,n=[];for(t in e)n[n.length]=t;return n})),$e=q((function(e){return null!=e&&Je(Number,e.length)?e.length:NaN})),Ze=U((function(e,t){return e=0;)o=e(o[0],n[r]),i[r]=o[1],r-=1;return[o[0],i]})),rt=U((function(e,t){return t.match(e)||[]})),it=U((function(e,t){return w(e)?!w(t)||t<1?NaN:(e%t+t)%t:NaN})),ot=U((function(e,t){return t>e?t:e})),st=D((function(e,t,n){return e(n)>e(t)?n:t})),at=D((function(e,t,n){var r,i={};for(r in t)m(r,t)&&(i[r]=m(r,n)?e(r,t[r],n[r]):t[r]);for(r in n)m(r,n)&&!m(r,i)&&(i[r]=n[r]);return i})),ct=U((function(e,t){return t0&&e(St(t,n))})),xt=U((function(e,t){for(var n={},r=0;r=0;)t=e(t,n[r]),r-=1;return t})),qt=q(C),Ut=D((function(e,t,n){return d(R(n,0,Math.min(e,n.length)),R(n,Math.min(n.length,e+t)))})),Dt=D((function(e,t,n){return n.replace(e,t)})),Vt=q((function(e){return T(e)?e.split("").reverse().join(""):R(e).reverse()})),Ft=D((function(e,t,n){for(var r=0,i=n.length,o=[t];ri?1:0}))})),zt=U((function(e,t){return[Ht(0,e,t),Ht(e,$e(t),t)]})),Jt=U((function(e,t){if(e<=0)throw new Error("First argument to splitEvery must be a positive integer");for(var n=[],r=0;r=0&&e(t[n]);)n-=1;return R(t,n+1,1/0)})),Zt=U(F("takeWhile",ne,(function(e,t){for(var n=0,r=t.length;n=0;){if(r[a]===t)return i[a]===n;a-=1}for(r.push(t),i.push(n),a=s.length-1;a>=0;){var c=s[a];if(!m(c,n)||!e(n[c],t[c],r,i))return!1;a-=1}return r.pop(),i.pop(),!0},Cn=function(e){return function t(n){for(var r,i,o,s=[],a=0,c=n.length;a=0&&e(t[n]);)n-=1;return R(t,0,n+1)}))),Bn=U((function(e,t){return Nn(e,t,[],[])})),Hn=U(F("filter",Y,(function(e,t){return O(t)?Rn((function(n,r){return e(t[r])&&(n[r]=t[r]),n}),{},Ke(t)):v(e,t)}))),Wn=q(Cn(!0)),Gn=q((function(e){return Un((function(t,n){var r=R(arguments);return r[0]=n,r[1]=t,e.apply(this,r)}))})),zn=U(F("groupBy",Mn,(function(e,t){return Rn((function(t,n){var r=e(n);return t[r]=le(n,t[r]||(t[r]=[])),t}),{},t)}))),Jn=vt(0),Qn=U((function(e,t){return Rn((function(t,n){return t[e(n)]=n,t}),{},t)})),Yn=Ht(0,-1),Kn=D((function(e,t,n){for(var r=[],i=0;i=0;){if(Bn(t[n],e))return n;n-=1}return-1}return t.lastIndexOf(e)})),nr=U(F("map",ee,(function(e,t){switch(Object.prototype.toString.call(t)){case"[object Function]":return ge(t.length,(function(){return e.call(this,t.apply(this,arguments))}));case"[object Object]":return Rn((function(n,r){return n[r]=e(t[r]),n}),{},Ke(t));default:return x(e,t)}}))),rr=U((function(e,t){return Rn((function(n,r){return n[r]=e(t[r],r,t),n}),{},Ke(t))})),ir=D((function(e,t,n){return at((function(t,n,r){return e(n,r)}),t,n)})),or=In(d),sr=In(Gn(d)),ar=U((function(e,t){return Rn((function(t,n){var r=t[e(n)?0:1];return r[r.length]=n,t}),[[],[]],t)})),cr=D((function(e,t,n){return Bn(St(e,n),t)})),ur=U((function(e,t){return nr(Ct(e),t)})),lr=bn(x,[At,Fe]),pr=D((function(e,t,n){return Pt(Bn(t),e,n)})),fr=D((function(e,t,n){return Pt(Je(e),t,n)})),hr=D(Rn),dr=U((function(e,t){return Hn(h(e),t)})),br=U((function(e,t){return tn(se(e),t)})),vr=hr(re,0),mr=U((function(e,t){return Dn(e>=0?t.length-e:0,t)})),yr=ge(4,(function(e,t,n,r){return Rn(e("function"==typeof t?j(t):t),n,r)})),gr=D((function(e,t,n){return fn(e,d(t,n))})),_r=U((function(e,t){return _n(nr(Bn,e),t)})),wr=function(e){var t=function(e){return{"@@transducer/init":M.init,"@@transducer/result":function(t){return e["@@transducer/result"](t)},"@@transducer/step":function(t,n){var r=e["@@transducer/step"](t,n);return r["@@transducer/reduced"]?{"@@transducer/value":r,"@@transducer/reduced":!0}:r}}}(e);return{"@@transducer/init":M.init,"@@transducer/result":function(e){return t["@@transducer/result"](e)},"@@transducer/step":function(e,n){return Qe(n)?Rn(t,e,n):Rn(t,e,[n])}}},Er=function(e,t,n){var r,i;if("function"==typeof e.indexOf)switch(o(t)){case"number":if(0===t){for(r=1/t;n=0)return!1;n+=1}return!0})),kr=q((function(e){return ge(hr(ot,0,ur("length",e)),(function(){for(var t=0,n=e.length;t10)throw new Error("Constructor with greater than ten arguments");return 0===e?function(){return new t}:Un(ft(e,(function(e,n,r,i,o,s,a,c,u,l){switch(arguments.length){case 1:return new t(e);case 2:return new t(e,n);case 3:return new t(e,n,r);case 4:return new t(e,n,r,i);case 5:return new t(e,n,r,i,o);case 6:return new t(e,n,r,i,o,s);case 7:return new t(e,n,r,i,o,s,a);case 8:return new t(e,n,r,i,o,s,a,c);case 9:return new t(e,n,r,i,o,s,a,c,u);case 10:return new t(e,n,r,i,o,s,a,c,u,l)}})))})),Rr=U((function(e,t){return ge(Math.max.apply(Math,ur("length",t)),(function(){var n=arguments,r=this;return e.apply(r,x((function(e){return e.apply(r,n)}),t))}))})),Pr=U(F("dropRepeatsWith",J,(function(e,t){var n=[],r=1,i=t.length;if(0!==i)for(n[0]=t[0];rt?1:0})).slice(r,r+n))})),Gr=ir((function(e,t){return t})),zr=q((function(e){return hr(Gr,{},e)})),Jr=function(){if(0===arguments.length)throw new Error("pipe requires at least one argument");return l(arguments[0].length,hr(A,arguments[0],Kt(arguments)))},Qr=function(){if(0===arguments.length)throw new Error("pipeP requires at least one argument");return l(arguments[0].length,hr(I,arguments[0],Kt(arguments)))},Yr=hr(pt,1),Kr=U((function(e,t){return"function"==typeof t.sequence?t.sequence(e):Lt((function(e,t){return xr(nr(Nt,t),e)}),e([]),t)})),Xr=D((function(e,t,n){return Kr(e,nr(t,n))})),$r=Ir(y),Zr=function(e,t){return Er(t,e,0)>=0},ei=(s={"@@transducer/init":Array,"@@transducer/step":function(e,t){return d(e,[t])},"@@transducer/result":y},a={"@@transducer/init":String,"@@transducer/step":function(e,t){return e+t},"@@transducer/result":y},c={"@@transducer/init":Object,"@@transducer/step":function(e,t){return Gr(e,Qe(t)?yt(t[0],t[1]):t)},"@@transducer/result":y},function(e){if(k(e))return e;if(Qe(e))return s;if("string"==typeof e)return a;if("object"===o(e))return c;throw new Error("Cannot create transformer for "+e)}),ti=function e(t,n){var r=function(r){var i=n.concat([t]);return Zr(r,i)?"":e(r,i)},i=function(e,t){return x((function(t){return N(t)+": "+r(e[t])}),t.slice().sort())};switch(Object.prototype.toString.call(t)){case"[object Arguments]":return"(function() { return arguments; }("+x(r,t).join(", ")+"))";case"[object Array]":return"["+x(r,t).concat(i(t,dr((function(e){return/^\d+$/.test(e)}),Ke(t)))).join(", ")+"]";case"[object Boolean]":return"object"===o(t)?"new Boolean("+r(t.valueOf())+")":t.toString();case"[object Date]":return"new Date("+(isNaN(t.valueOf())?r(NaN):N(P(t)))+")";case"[object Null]":return"null";case"[object Number]":return"object"===o(t)?"new Number("+r(t.valueOf())+")":1/t==-1/0?"-0":t.toString(10);case"[object String]":return"object"===o(t)?"new String("+r(t.valueOf())+")":N(t);case"[object Undefined]":return"undefined";default:if("function"==typeof t.toString){var s=t.toString();if("[object Object]"!==s)return s}return"{"+i(t,Ke(t)).join(", ")+"}"}},ni=Nr(Fe),ri=function(){if(0===arguments.length)throw new Error("compose requires at least one argument");return Jr.apply(this,Vt(arguments))},ii=function(){return ri.apply(this,Nt(Fe,nr(Ir,arguments)))},oi=q((function(e){return Cr(e.length,e)})),si=U(Zr),ai=U((function(e,t){for(var n=[],r=0,i=e.length;rc&&(u.push(r),c=i);break;case"object":if(null===n){l||(l=!0,u.push(null));break}default:Zr(n,a)||(a.push(n),u.push(r))}f+=1}return u}),di=U((function(e,t){return dr(Gn(Zr)(e),t)})),bi=li(bt),vi=U((function(e,t){return ge(e+1,(function(){var n=arguments[e];if(null!=n&&Je(Function,n[t]))return n[t].apply(n,R(arguments,0,e));throw new TypeError(fi(n)+' does not have a method named "'+t+'"')}))})),mi=vi(1,"join"),yi=q((function(e){var t={};return l(e.length,(function(){var n=fi(arguments);return m(n,t)||(t[n]=e.apply(this,arguments)),t[n]}))})),gi=vi(1,"split"),_i=U((function(e,t){if(n=e,"[object RegExp]"!==Object.prototype.toString.call(n))throw new TypeError("‘test’ requires a value of type RegExp as its first argument; received "+fi(e));var n;return f(e).test(t)})),wi=vi(0,"toLowerCase"),Ei=vi(0,"toUpperCase"),Oi=hi(Fe),Si=Gn(vi(1,"concat")),Ti=U((function(e,t){return Oi(v(Gn(Zr)(e),t))})),ki=U((function(e,t){return Si(ai(e,t),ai(t,e))})),xi=D((function(e,t,n){return Si(Ee(e,t,n),Ee(e,n,t))})),Ai=U(ri(Oi,d)),Ii={F:kn,T:xn,__:u,add:re,addIndex:jn,adjust:ie,all:oe,allPass:Sr,allUniq:Tr,always:se,and:ae,any:ce,anyPass:kr,ap:xr,aperture:ue,append:le,apply:pe,assoc:fe,assocPath:he,binary:Ln,bind:de,both:be,call:Ar,chain:Ir,clone:qn,commute:ni,commuteMap:Nr,comparator:ve,complement:bi,compose:ri,composeK:ii,composeP:function(){if(0===arguments.length)throw new Error("composeP requires at least one argument");return Qr.apply(this,Vt(arguments))},concat:Si,cond:me,construct:oi,constructN:Cr,contains:si,converge:Rr,countBy:ye,curry:Un,curryN:ge,dec:_e,defaultTo:we,difference:ai,differenceWith:Ee,dissoc:Oe,dissocPath:Se,divide:Te,drop:Dn,dropLast:Vn,dropLastWhile:Fn,dropRepeats:ci,dropRepeatsWith:Pr,dropWhile:ke,either:xe,empty:Ae,eqBy:Mr,eqProps:jr,equals:Bn,evolve:Ie,filter:Hn,find:Ne,findIndex:Ce,findLast:Re,findLastIndex:Pe,flatten:Wn,flip:Gn,forEach:Me,fromPairs:je,groupBy:zn,gt:Le,gte:qe,has:Ue,hasIn:De,head:Jn,identical:Ve,identity:Fe,ifElse:Be,inc:He,indexBy:Qn,indexOf:Lr,init:Yn,insert:We,insertAll:Ge,intersection:Ti,intersectionWith:Kn,intersperse:ze,into:ui,invert:Xn,invertObj:$n,invoker:vi,is:Je,isArrayLike:Qe,isEmpty:Zn,isNil:Ye,join:mi,juxt:qr,keys:Ke,keysIn:Xe,last:er,lastIndexOf:tr,length:$e,lens:Ur,lensIndex:Dr,lensPath:Vr,lensProp:Fr,lift:li,liftN:Br,lt:Ze,lte:et,map:nr,mapAccum:tt,mapAccumRight:nt,mapObjIndexed:rr,match:rt,mathMod:it,max:ot,maxBy:st,mean:Hr,median:Wr,memoize:yi,merge:Gr,mergeAll:zr,mergeWith:ir,mergeWithKey:at,min:ct,minBy:ut,modulo:lt,multiply:pt,nAry:ft,negate:ht,none:dt,not:bt,nth:vt,nthArg:mt,objOf:yt,of:gt,omit:pi,once:_t,or:wt,over:Et,pair:Ot,partial:or,partialRight:sr,partition:ar,path:St,pathEq:cr,pathOr:Tt,pathSatisfies:kt,pick:xt,pickAll:At,pickBy:It,pipe:Jr,pipeK:function(){return ii.apply(this,Vt(arguments))},pipeP:Qr,pluck:ur,prepend:Nt,product:Yr,project:lr,prop:Ct,propEq:pr,propIs:fr,propOr:Rt,propSatisfies:Pt,props:Mt,range:jt,reduce:hr,reduceRight:Lt,reduced:qt,reject:dr,remove:Ut,repeat:br,replace:Dt,reverse:Vt,scan:Ft,sequence:Kr,set:Bt,slice:Ht,sort:Wt,sortBy:Gt,split:gi,splitAt:zt,splitEvery:Jt,splitWhen:Qt,subtract:Yt,sum:vr,symmetricDifference:ki,symmetricDifferenceWith:xi,tail:Kt,take:Xt,takeLast:mr,takeLastWhile:$t,takeWhile:Zt,tap:en,test:_i,times:tn,toLower:wi,toPairs:nn,toPairsIn:rn,toString:fi,toUpper:Ei,transduce:yr,transpose:on,traverse:Xr,trim:sn,type:an,unapply:cn,unary:un,uncurryN:ln,unfold:pn,union:Ai,unionWith:gr,uniq:Oi,uniqBy:hi,uniqWith:fn,unless:hn,unnest:$r,update:dn,useWith:bn,values:vn,valuesIn:mn,view:yn,when:gn,where:_n,whereEq:_r,without:di,wrap:wn,xprod:En,zip:On,zipObj:Sn,zipWith:Tn};e.exports=Ii}).call(O)})),x={enabled:!0},A=function(e,t,n,r,i){t||(t=6e4),void 0===n&&(n=2),void 0===r&&(r=.5),i||(i=Math.random);var o=null,s=function(s){if(!x.enabled)return 6048e5;var a=e*Math.pow(n,s);o&&(a=Math.max(a,o),o=null);var c=i(),u=Math.floor(c*r*a),l=Math.floor(10*c)%2==0?a-u:a+u;return a=Math.min(l,t),x.maxDelay&&a>x.maxDelay?x.maxDelay:x.minDelay&&a<=x.minDelay?x.minDelay:a};return s.setNextDelayMinimum=function(e){o=e},s.maximizeNextDelay=function(){return s.setNextDelayMinimum(t)},s},I=function e(t){var n=t.calculateAttemptDelay,r=t.attempt,i=t.onGiveUp,o=t.retryLimit,s=t.retryCount,a=function(t){return r({context:{retryLimit:o,retryCount:s,delay:t},repeat:function(t){return 0===o||s=300?s():e()},a.onerror=function(){return s()},a.send(i(o))}))}}},B=function(e){return function(t){var n=t.namespace;return{attempted:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.tags,i=void 0===r?[]:r,o=Date.now(),s=!1,a=function(t){var r=t.action,o=t.reason,s=["action:".concat(r)];return o&&s.push("reason:".concat(o)),e.increment("sm.lib.".concat(n),k.concat(i,s))},c=function(e){return a({action:"failed",reason:e})},u=function(t){var r=t.action;s=!0;var a=Date.now()-o;e.histogram("sm.timing.lib.".concat(n),a,k.concat(i,["client:browser","action:".concat(r)]))};return a({action:"attempted"}),{succeeded:function(){a({action:"succeeded"}),u({action:"succeeded"})},failed:function(e){c(e),u({action:"failed"})},timedOut:function(){c("timed_out"),u({action:"failed"})},failedUnknown:function(){c("unknown"),u({action:"failed"})},isFinished:function(){return s}}}}}},H=["timing","increment","decrement","gauge","histogram","set"],W=function(){function e(){var t=this;s(this,e),this.withTags=this.withTags.bind(this),this.instrument=function(){return{attempted:function(){return{succeeded:function(){},failed:function(){},timedOut:function(){},failedUnknown:function(){},isFinished:function(){}}}}},H.forEach((function(e){t[e]=function(){}}))}return c(e,[{key:"recordMessageHubConnectionEstablished",value:function(){}},{key:"recordBaseDomCaching",value:function(){}},{key:"clientHandlerError",value:function(){}},{key:"statApiUsage",value:function(e){e.resource;return function(e){return{attempted:function(){return{succeeded:function(){},failed:function(){},timedOut:function(){},failedUnknown:function(){},isFinished:function(){}}}}}}},{key:"statScreenShareUsage",value:function(e,t){return{attempted:function(){return{succeeded:function(){},failed:function(){},timedOut:function(){},failedUnknown:function(){},isFinished:function(){}}}}}},{key:"withTags",value:function(){return this}}]),e}(),G=function(){function e(t,n){var r=this;s(this,e),this.statApiUsage=this.statApiUsage.bind(this),this.statScreenShareUsage=this.statScreenShareUsage.bind(this),this.withTags=this.withTags.bind(this),this.statsClient=t,this.latencyMeasurer=n,this.instrument=B(this.statsClient),H.forEach((function(e){r.statsClient[e]&&(r[e]=r.statsClient[e].bind(r.statsClient))}))}return c(e,[{key:"recordBaseDomCaching",value:function(e){var t=e.result;this.statsClient.increment("sm.app.visitor.api.cached_base_dom",["action:save","result:".concat(t)])}},{key:"clientHandlerError",value:function(e){this.statsClient.increment("sm.app.visitor.api.client_handler",["action:failed","executor:".concat(e)])}},{key:"statApiUsage",value:function(e){var t=this,n=e.protocol,r=e.resource;return function(e){return B(t.statsClient.withTags(["protocol:".concat(n),"method:".concat(e)]))({namespace:r})}}},{key:"statScreenShareUsage",value:function(e){var t=e.stage,n=e.resource;return B(this.statsClient.withTags(["stage:".concat(t)]))({namespace:n})}},{key:"withTags",value:function(t){return new e(this.statsClient.withTags(t))}}],[{key:"createDummy",value:function(){return new W}}]),e}(),z="undefined"!=typeof window&&window,J="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Q=z||void 0!==O&&O||J,Y=Q;!function(){if(!Q)throw new Error("RxJS could not find any global context (window, self, global)")}();var K={root:Y};var X={isFunction:function(e){return"function"==typeof e}},$={isArray:Array.isArray||function(e){return e&&"number"==typeof e.length}};var Z,ee={isObject:function(e){return null!=e&&"object"===o(e)}},te={errorObject:{e:{}}};function ne(){try{return Z.apply(this,arguments)}catch(e){return te.errorObject.e=e,te.errorObject}}var re={tryCatch:function(e){return Z=e,ne}},ie=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},oe={UnsubscriptionError:function(e){function t(t){e.call(this),this.errors=t;var n=Error.call(this,t?t.length+" errors occurred during unsubscription:\n "+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"");this.name=n.name="UnsubscriptionError",this.stack=n.stack,this.message=n.message}return ie(t,e),t}(Error)},se=function(){function e(e){this.closed=!1,this._parent=null,this._parents=null,this._subscriptions=null,e&&(this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var e,t=!1;if(!this.closed){var n=this,r=n._parent,i=n._parents,o=n._unsubscribe,s=n._subscriptions;this.closed=!0,this._parent=null,this._parents=null,this._subscriptions=null;for(var a=-1,c=i?i.length:0;r;)r.remove(this),r=++a1?new t(e,r):1===i?new Qe.ScalarObservable(e[0],r):new Ke.EmptyObservable(r)},t.dispatch=function(e){var t=e.array,n=e.index,r=e.count,i=e.subscriber;n>=r?i.complete():(i.next(t[n]),i.closed||(e.index=n+1,this.schedule(e)))},t.prototype._subscribe=function(e){var n=this.array,r=n.length,i=this.scheduler;if(i)return i.schedule(t.dispatch,0,{array:n,index:0,count:r,subscriber:e});for(var o=0;oxt)return xt;return t}(e)),this.arr=e,this.idx=t,this.len=n}return e.prototype[rt.iterator]=function(){return this},e.prototype.next=function(){return this.idx=r?i.complete():(i.next(t[n]),e.index=n+1,this.schedule(e)))},t.prototype._subscribe=function(e){var n=this.arrayLike,r=this.scheduler,i=n.length;if(r)return r.schedule(t.dispatch,0,{arrayLike:n,index:0,length:i,subscriber:e});for(var o=0;o0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(et.OuterSubscriber),Qt={mergeMap:Wt,MergeMapOperator:zt,MergeMapSubscriber:Jt};var Yt={identity:function(e){return e}};var Kt={mergeAll:function(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),Qt.mergeMap(Yt.identity,null,e)}};var Xt={concatAll:function(){return Kt.mergeAll(1)}};var $t={concat:function(){for(var e=[],t=0;t=0}},Tn=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},kn={Action:function(e){function t(t,n){e.call(this)}return Tn(t,e),t.prototype.schedule=function(e,t){return this},t}(ce.Subscription)},xn=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},An={AsyncAction:function(e){function t(t,n){e.call(this,t,n),this.scheduler=t,this.pending=!1,this.work=n}return xn(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e,this.pending=!0;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,t)),this.delay=t,this.id=this.id||this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return void 0===n&&(n=0),K.root.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(void 0===n&&(n=0),null!==n&&this.delay===n&&!1===this.pending)return t;K.root.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n=!1,r=void 0;try{this.work(e)}catch(e){n=!0,r=!!e&&e||new Error(e)}if(n)return this.unsubscribe(),r},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,n=t.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(kn.Action)},In={Scheduler:function(){function e(t,n){void 0===n&&(n=e.now),this.SchedulerAction=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(n,t)},e.now=Date.now?Date.now:function(){return+new Date},e}()},Nn=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},Cn={AsyncScheduler:function(e){function t(){e.apply(this,arguments),this.actions=[],this.active=!1,this.scheduled=void 0}return Nn(t,e),t.prototype.flush=function(e){var t=this.actions;if(this.active)t.push(e);else{var n;this.active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this.active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(In.Scheduler)},Rn={async:new Cn.AsyncScheduler(An.AsyncAction)},Pn=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},Mn={IntervalObservable:function(e){function t(t,n){void 0===t&&(t=0),void 0===n&&(n=Rn.async),e.call(this),this.period=t,this.scheduler=n,(!Sn.isNumeric(t)||t<0)&&(this.period=0),n&&"function"==typeof n.schedule||(this.scheduler=Rn.async)}return Pn(t,e),t.create=function(e,n){return void 0===e&&(e=0),void 0===n&&(n=Rn.async),new t(e,n)},t.dispatch=function(e){var t=e.index,n=e.subscriber,r=e.period;n.next(t),n.closed||(e.index+=1,this.schedule(e,r))},t.prototype._subscribe=function(e){var n=this.period,r=this.scheduler;e.add(r.schedule(t.dispatch,n,{index:0,subscriber:e,period:n}))},t}(Oe.Observable)}.IntervalObservable.create,jn={interval:Mn};Oe.Observable.interval=jn.interval;var Ln=function(){for(var e=[],t=0;t1&&"number"==typeof e[e.length-1]&&(n=e.pop())):"number"==typeof i&&(n=e.pop()),null===r&&1===e.length&&e[0]instanceof Oe.Observable?e[0]:Kt.mergeAll(n)(new $e.ArrayObservable(e,r))},qn={merge:Ln};Oe.Observable.merge=qn.merge;var Un=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Dn=function(){for(var e=[],t=0;t=r?i.complete():(i.next(t),i.closed||(e.index=n+1,e.start=t+1,this.schedule(e)))},t.prototype._subscribe=function(e){var n=0,r=this.start,i=this._count,o=this.scheduler;if(o)return o.schedule(t.dispatch,0,{index:n,count:i,start:r,subscriber:e});for(;;){if(n++>=i){e.complete();break}if(e.next(r++),e.closed)break}},t}(Oe.Observable)}.RangeObservable.create};Oe.Observable.range=rr.range;var ir=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},or=function(e){function t(t,n){e.call(this),this.resourceFactory=t,this.observableFactory=n}return ir(t,e),t.create=function(e,n){return new t(e,n)},t.prototype._subscribe=function(e){var t,n=this.resourceFactory,r=this.observableFactory;try{return t=n(),new sr(e,t,r)}catch(t){e.error(t)}},t}(Oe.Observable),sr=function(e){function t(t,n,r){e.call(this,t),this.resource=n,this.observableFactory=r,t.add(n),this.tryUse()}return ir(t,e),t.prototype.tryUse=function(){try{var e=this.observableFactory.call(this,this.resource);e&&this.add(st.subscribeToResult(this,e))}catch(e){this._error(e)}},t}(et.OuterSubscriber),ar={using:{UsingObservable:or}.UsingObservable.create};Oe.Observable.using=ar.using;var cr=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},ur={ErrorObservable:function(e){function t(t,n){e.call(this),this.error=t,this.scheduler=n}return cr(t,e),t.create=function(e,n){return new t(e,n)},t.dispatch=function(e){var t=e.error;e.subscriber.error(t)},t.prototype._subscribe=function(e){var n=this.error,r=this.scheduler;if(e.syncErrorThrowable=!0,r)return r.schedule(t.dispatch,0,{error:n,subscriber:e});e.error(n)},t}(Oe.Observable)}.ErrorObservable.create,lr={_throw:ur};Oe.Observable.throw=lr._throw;var pr={isDate:function(e){return e instanceof Date&&!isNaN(+e)}},fr=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},hr={TimerObservable:function(e){function t(t,n,r){void 0===t&&(t=0),e.call(this),this.period=-1,this.dueTime=0,Sn.isNumeric(n)?this.period=Number(n)<1?1:Number(n):ze.isScheduler(n)&&(r=n),ze.isScheduler(r)||(r=Rn.async),this.scheduler=r,this.dueTime=pr.isDate(t)?+t-this.scheduler.now():t}return fr(t,e),t.create=function(e,n,r){return void 0===e&&(e=0),new t(e,n,r)},t.dispatch=function(e){var t=e.index,n=e.period,r=e.subscriber;if(r.next(t),!r.closed){if(-1===n)return r.complete();e.index=t+1,this.schedule(e,n)}},t.prototype._subscribe=function(e){var n=this,r=n.period,i=n.dueTime;return n.scheduler.schedule(t.dispatch,i,{index:0,period:r,subscriber:e})},t}(Oe.Observable)}.TimerObservable.create,dr={timer:hr};Oe.Observable.timer=dr.timer;var br=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var vr=function(){for(var e=[],t=0;tthis.index},e.prototype.hasCompleted=function(){return this.array.length===this.index},e}(),Tr=function(e){function t(t,n,r){e.call(this,t),this.parent=n,this.observable=r,this.stillUnsubscribed=!0,this.buffer=[],this.isComplete=!1}return br(t,e),t.prototype[rt.iterator]=function(){return this},t.prototype.next=function(){var e=this.buffer;return 0===e.length&&this.isComplete?{value:null,done:!0}:{value:e.shift(),done:!1}},t.prototype.hasValue=function(){return this.buffer.length>0},t.prototype.hasCompleted=function(){return 0===this.buffer.length&&this.isComplete},t.prototype.notifyComplete=function(){this.buffer.length>0?(this.isComplete=!0,this.parent.notifyInactive()):this.destination.complete()},t.prototype.notifyNext=function(e,t,n,r,i){this.buffer.push(t),this.parent.checkIterators()},t.prototype.subscribe=function(e,t){return st.subscribeToResult(this,this.observable,this,t)},t}(et.OuterSubscriber),kr={zip:vr,zipStatic:yr,ZipOperator:_r,ZipSubscriber:Er},xr={zip:kr.zipStatic};Oe.Observable.zip=xr.zip;var Ar=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Ir=function(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new Nr(e,t))}},Nr=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Rr(e,this.project,this.thisArg))},e}(),Cr=Nr,Rr=function(e){function t(t,n,r){e.call(this,t),this.project=n,this.count=0,this.thisArg=r||this}return Ar(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(ve.Subscriber),Pr={map:Ir,MapOperator:Cr},Mr=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};function jr(){if(K.root.XMLHttpRequest)return new K.root.XMLHttpRequest;if(K.root.XDomainRequest)return new K.root.XDomainRequest;throw new Error("CORS is not supported by your browser")}function Lr(e,t){return void 0===t&&(t=null),new Yr({method:"GET",url:e,headers:t})}var qr=Lr;function Ur(e,t,n){return new Yr({method:"POST",url:e,body:t,headers:n})}var Dr=Ur;function Vr(e,t){return new Yr({method:"DELETE",url:e,headers:t})}var Fr=Vr;function Br(e,t,n){return new Yr({method:"PUT",url:e,body:t,headers:n})}var Hr=Br;function Wr(e,t,n){return new Yr({method:"PATCH",url:e,body:t,headers:n})}var Gr=Wr,zr=Pr.map((function(e,t){return e.response}));function Jr(e,t){return zr(new Yr({method:"GET",url:e,responseType:"json",headers:t}))}var Qr=Jr,Yr=function(e){function t(t){e.call(this);var n={async:!0,createXHR:function(){return this.crossDomain?jr.call(this):function(){if(K.root.XMLHttpRequest)return new K.root.XMLHttpRequest;var e=void 0;try{for(var t=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],n=0;n<3;n++)try{if(e=t[n],new K.root.ActiveXObject(e))break}catch(e){}return new K.root.ActiveXObject(e)}catch(e){throw new Error("XMLHttpRequest is not supported by your browser")}}()},crossDomain:!1,withCredentials:!1,headers:{},method:"GET",responseType:"json",timeout:0};if("string"==typeof t)n.url=t;else for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r]);this.request=n}return Mr(t,e),t.prototype._subscribe=function(e){return new Xr(e,this.request)},t.create=function(){var e=function(e){return new t(e)};return e.get=Lr,e.post=Ur,e.delete=Vr,e.put=Br,e.patch=Wr,e.getJSON=Jr,e}(),t}(Oe.Observable),Kr=Yr,Xr=function(e){function t(t,n){e.call(this,t),this.request=n,this.done=!1;var r=n.headers=n.headers||{};n.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest"),"Content-Type"in r||K.root.FormData&&n.body instanceof K.root.FormData||void 0===n.body||(r["Content-Type"]="application/x-www-form-urlencoded; charset=UTF-8"),n.body=this.serializeBody(n.body,n.headers["Content-Type"]),this.send()}return Mr(t,e),t.prototype.next=function(e){this.done=!0;var t=this,n=t.xhr,r=t.request,i=t.destination,o=new Zr(e,n,r);i.next(o)},t.prototype.send=function(){var e=this.request,t=this.request,n=t.user,r=t.method,i=t.url,o=t.async,s=t.password,a=t.headers,c=t.body,u=e.createXHR,l=re.tryCatch(u).call(e);if(l===te.errorObject)this.error(te.errorObject.e);else{this.xhr=l,this.setupEvents(l,e);if((n?re.tryCatch(l.open).call(l,r,i,o,n,s):re.tryCatch(l.open).call(l,r,i,o))===te.errorObject)return this.error(te.errorObject.e),null;if(o&&(l.timeout=e.timeout,l.responseType=e.responseType),"withCredentials"in l&&(l.withCredentials=!!e.withCredentials),this.setHeaders(l,a),(c?re.tryCatch(l.send).call(l,c):re.tryCatch(l.send).call(l))===te.errorObject)return this.error(te.errorObject.e),null}return l},t.prototype.serializeBody=function(e,t){if(!e||"string"==typeof e)return e;if(K.root.FormData&&e instanceof K.root.FormData)return e;if(t){var n=t.indexOf(";");-1!==n&&(t=t.substring(0,n))}switch(t){case"application/x-www-form-urlencoded":return Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&");case"application/json":return JSON.stringify(e);default:return e}},t.prototype.setHeaders=function(e,t){for(var n in t)t.hasOwnProperty(n)&&e.setRequestHeader(n,t[n])},t.prototype.setupEvents=function(e,t){var n=t.progressSubscriber;function r(e){var t=r,n=t.subscriber,i=t.progressSubscriber,o=t.request;i&&i.error(e),n.error(new ii(this,o))}if(e.ontimeout=r,r.request=t,r.subscriber=this,r.progressSubscriber=n,e.upload&&"withCredentials"in e){var i,o;if(n)i=function(e){i.progressSubscriber.next(e)},K.root.XDomainRequest?e.onprogress=i:e.upload.onprogress=i,i.progressSubscriber=n;o=function(e){var t=o,n=t.progressSubscriber,r=t.subscriber,i=t.request;n&&n.error(e),r.error(new ti("ajax error",this,i))},e.onerror=o,o.request=t,o.subscriber=this,o.progressSubscriber=n}function s(e){var t=s,n=t.subscriber,r=t.progressSubscriber,i=t.request;if(4===this.readyState){var o=1223===this.status?204:this.status,a="text"===this.responseType?this.response||this.responseText:this.response;0===o&&(o=a?200:0),200<=o&&o<300?(r&&r.complete(),n.next(e),n.complete()):(r&&r.error(e),n.error(new ti("ajax error "+o,this,i)))}}e.onreadystatechange=s,s.subscriber=this,s.progressSubscriber=n,s.request=t},t.prototype.unsubscribe=function(){var t=this.done,n=this.xhr;!t&&n&&4!==n.readyState&&"function"==typeof n.abort&&n.abort(),e.prototype.unsubscribe.call(this)},t}(ve.Subscriber),$r=Xr,Zr=function(e,t,n){this.originalEvent=e,this.xhr=t,this.request=n,this.status=t.status,this.responseType=t.responseType||n.responseType,this.response=ri(this.responseType,t)},ei=Zr,ti=function(e){function t(t,n,r){e.call(this,t),this.message=t,this.xhr=n,this.request=r,this.status=n.status,this.responseType=n.responseType||r.responseType,this.response=ri(this.responseType,n)}return Mr(t,e),t}(Error),ni=ti;function ri(e,t){switch(e){case"json":return"response"in t?t.responseType?t.response:JSON.parse(t.response||t.responseText||"null"):JSON.parse(t.responseText||"null");case"xml":return t.responseXML;case"text":default:return"response"in t?t.response:t.responseText}}var ii=function(e){function t(t,n){e.call(this,"ajax timeout",t,n)}return Mr(t,e),t}(ti),oi={ajaxGet:qr,ajaxPost:Dr,ajaxDelete:Fr,ajaxPut:Hr,ajaxPatch:Gr,ajaxGetJSON:Qr,AjaxObservable:Kr,AjaxSubscriber:$r,AjaxResponse:ei,AjaxError:ni,AjaxTimeoutError:ii},si={ajax:oi.AjaxObservable.create};Oe.Observable.ajax=si.ajax;var ai=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},ci={QueueAction:function(e){function t(t,n){e.call(this,t,n),this.scheduler=t,this.work=n}return ai(t,e),t.prototype.schedule=function(t,n){return void 0===n&&(n=0),n>0?e.prototype.schedule.call(this,t,n):(this.delay=n,this.state=t,this.scheduler.flush(this),this)},t.prototype.execute=function(t,n){return n>0||this.closed?e.prototype.execute.call(this,t,n):this._execute(t,n)},t.prototype.requestAsyncId=function(t,n,r){return void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0?e.prototype.requestAsyncId.call(this,t,n,r):t.flush(this)},t}(An.AsyncAction)},ui=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},li={queue:new({QueueScheduler:function(e){function t(){e.apply(this,arguments)}return ui(t,e),t}(Cn.AsyncScheduler)}.QueueScheduler)(ci.QueueAction)},pi=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},fi=function(e){function t(t,n,r){void 0===t&&(t=Number.POSITIVE_INFINITY),void 0===n&&(n=Number.POSITIVE_INFINITY),e.call(this),this.scheduler=r,this._events=[],this._bufferSize=t<1?1:t,this._windowTime=n<1?1:n}return pi(t,e),t.prototype.next=function(t){var n=this._getNow();this._events.push(new hi(n,t)),this._trimBufferThenGetEvents(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){var t,n=this._trimBufferThenGetEvents(),r=this.scheduler;if(this.closed)throw new Te.ObjectUnsubscribedError;this.hasError||this.isStopped?t=ce.Subscription.EMPTY:(this.observers.push(e),t=new xe.SubjectSubscription(this,e)),r&&e.add(e=new Ut.ObserveOnSubscriber(e,r));for(var i=n.length,o=0;ot&&(o=Math.max(o,i-t)),o>0&&r.splice(0,o),r},t}(Me.Subject),hi=function(e,t){this.time=e,this.value=t},di={ReplaySubject:fi};function bi(e){for(var t=[],n=1;n0&&this.destination.next(t),e.prototype._complete.call(this)},t}(ve.Subscriber),Ni=function(e){function t(t,n,r){e.call(this,t),this.bufferSize=n,this.startBufferEvery=r,this.buffers=[],this.count=0}return ki(t,e),t.prototype._next=function(e){var t=this,n=t.bufferSize,r=t.startBufferEvery,i=t.buffers,o=t.count;this.count++,o%r==0&&i.push([]);for(var s=i.length;s--;){var a=i[s];a.push(e),a.length===n&&(i.splice(s,1),this.destination.next(a))}},t.prototype._complete=function(){for(var t=this.buffers,n=this.destination;t.length>0;){var r=t.shift();r.length>0&&n.next(r)}e.prototype._complete.call(this)},t}(ve.Subscriber),Ci={bufferCount:xi};var Ri={bufferCount:function(e,t){return void 0===t&&(t=null),Ci.bufferCount(e,t)(this)}};Oe.Observable.prototype.bufferCount=Ri.bufferCount;var Pi=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Mi=function(e){var t=arguments.length,n=Rn.async;ze.isScheduler(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],t--);var r=null;t>=2&&(r=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),function(t){return t.lift(new ji(e,r,i,n))}},ji=function(){function e(e,t,n,r){this.bufferTimeSpan=e,this.bufferCreationInterval=t,this.maxBufferSize=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new qi(e,this.bufferTimeSpan,this.bufferCreationInterval,this.maxBufferSize,this.scheduler))},e}(),Li=function(){this.buffer=[]},qi=function(e){function t(t,n,r,i,o){e.call(this,t),this.bufferTimeSpan=n,this.bufferCreationInterval=r,this.maxBufferSize=i,this.scheduler=o,this.contexts=[];var s=this.openContext();if(this.timespanOnly=null==r||r<0,this.timespanOnly){var a={subscriber:this,context:s,bufferTimeSpan:n};this.add(s.closeAction=o.schedule(Ui,n,a))}else{var c={subscriber:this,context:s},u={bufferTimeSpan:n,bufferCreationInterval:r,subscriber:this,scheduler:o};this.add(s.closeAction=o.schedule(Vi,n,c)),this.add(o.schedule(Di,r,u))}}return Pi(t,e),t.prototype._next=function(e){for(var t,n=this.contexts,r=n.length,i=0;i0;){var r=t.shift();n.next(r.buffer)}e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.contexts=null},t.prototype.onBufferFull=function(e){this.closeContext(e);var t=e.closeAction;if(t.unsubscribe(),this.remove(t),!this.closed&&this.timespanOnly){e=this.openContext();var n=this.bufferTimeSpan,r={subscriber:this,context:e,bufferTimeSpan:n};this.add(e.closeAction=this.scheduler.schedule(Ui,n,r))}},t.prototype.openContext=function(){var e=new Li;return this.contexts.push(e),e},t.prototype.closeContext=function(e){this.destination.next(e.buffer);var t=this.contexts;(t?t.indexOf(e):-1)>=0&&t.splice(t.indexOf(e),1)},t}(ve.Subscriber);function Ui(e){var t=e.subscriber,n=e.context;n&&t.closeContext(n),t.closed||(e.context=t.openContext(),e.context.closeAction=this.schedule(e,e.bufferTimeSpan))}function Di(e){var t=e.bufferCreationInterval,n=e.bufferTimeSpan,r=e.subscriber,i=e.scheduler,o=r.openContext();r.closed||(r.add(o.closeAction=i.schedule(Vi,n,{subscriber:r,context:o})),this.schedule(e,t))}function Vi(e){var t=e.subscriber,n=e.context;t.closeContext(n)}var Fi={bufferTime:Mi};var Bi={bufferTime:function(e){var t=arguments.length,n=Rn.async;ze.isScheduler(arguments[arguments.length-1])&&(n=arguments[arguments.length-1],t--);var r=null;t>=2&&(r=arguments[1]);var i=Number.POSITIVE_INFINITY;return t>=3&&(i=arguments[2]),Fi.bufferTime(e,r,i,n)(this)}};Oe.Observable.prototype.bufferTime=Bi.bufferTime;var Hi=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Wi=function(e,t){return function(n){return n.lift(new Gi(e,t))}},Gi=function(){function e(e,t){this.openings=e,this.closingSelector=t}return e.prototype.call=function(e,t){return t.subscribe(new zi(e,this.openings,this.closingSelector))},e}(),zi=function(e){function t(t,n,r){e.call(this,t),this.openings=n,this.closingSelector=r,this.contexts=[],this.add(st.subscribeToResult(this,n))}return Hi(t,e),t.prototype._next=function(e){for(var t=this.contexts,n=t.length,r=0;r0;){var r=n.shift();r.subscription.unsubscribe(),r.buffer=null,r.subscription=null}this.contexts=null,e.prototype._error.call(this,t)},t.prototype._complete=function(){for(var t=this.contexts;t.length>0;){var n=t.shift();this.destination.next(n.buffer),n.subscription.unsubscribe(),n.buffer=null,n.subscription=null}this.contexts=null,e.prototype._complete.call(this)},t.prototype.notifyNext=function(e,t,n,r,i){e?this.closeBuffer(e):this.openBuffer(t)},t.prototype.notifyComplete=function(e){this.closeBuffer(e.context)},t.prototype.openBuffer=function(e){try{var t=this.closingSelector.call(this,e);t&&this.trySubscribe(t)}catch(e){this._error(e)}},t.prototype.closeBuffer=function(e){var t=this.contexts;if(t&&e){var n=e.buffer,r=e.subscription;this.destination.next(n),t.splice(t.indexOf(e),1),this.remove(r),r.unsubscribe()}},t.prototype.trySubscribe=function(e){var t=this.contexts,n=new ce.Subscription,r={buffer:[],subscription:n};t.push(r);var i=st.subscribeToResult(this,e,r);!i||i.closed?this.closeBuffer(r):(i.context=r,this.add(i),n.add(i))},t}(et.OuterSubscriber),Ji={bufferToggle:Wi};var Qi={bufferToggle:function(e,t){return Ji.bufferToggle(e,t)(this)}};Oe.Observable.prototype.bufferToggle=Qi.bufferToggle;var Yi=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Ki=function(e){return function(t){return t.lift(new Xi(e))}},Xi=function(){function e(e){this.closingSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new $i(e,this.closingSelector))},e}(),$i=function(e){function t(t,n){e.call(this,t),this.closingSelector=n,this.subscribing=!1,this.openBuffer()}return Yi(t,e),t.prototype._next=function(e){this.buffer.push(e)},t.prototype._complete=function(){var t=this.buffer;t&&this.destination.next(t),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){this.buffer=null,this.subscribing=!1},t.prototype.notifyNext=function(e,t,n,r,i){this.openBuffer()},t.prototype.notifyComplete=function(){this.subscribing?this.complete():this.openBuffer()},t.prototype.openBuffer=function(){var e=this.closingSubscription;e&&(this.remove(e),e.unsubscribe());var t=this.buffer;this.buffer&&this.destination.next(t),this.buffer=[];var n=re.tryCatch(this.closingSelector)();n===te.errorObject?this.error(te.errorObject.e):(e=new ce.Subscription,this.closingSubscription=e,this.add(e),this.subscribing=!0,e.add(st.subscribeToResult(this,n)),this.subscribing=!1)},t}(et.OuterSubscriber),Zi={bufferWhen:Ki};var eo={bufferWhen:function(e){return Zi.bufferWhen(e)(this)}};Oe.Observable.prototype.bufferWhen=eo.bufferWhen;var to=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var no=function(e){return function(t){var n=new ro(e),r=t.lift(n);return n.caught=r}},ro=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new io(e,this.selector,this.caught))},e}(),io=function(e){function t(t,n,r){e.call(this,t),this.selector=n,this.caught=r}return to(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=void 0;try{n=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle(),this.add(st.subscribeToResult(this,n))}},t}(et.OuterSubscriber),oo={catchError:no};var so={_catch:function(e){return oo.catchError(e)(this)}};Oe.Observable.prototype.catch=so._catch,Oe.Observable.prototype._catch=so._catch;var ao={combineAll:function(e){return function(t){return t.lift(new ht.CombineLatestOperator(e))}}};var co={combineAll:function(e){return ao.combineAll(e)(this)}};Oe.Observable.prototype.combineAll=co.combineAll;var uo={combineLatest:function(){for(var e=[],t=0;t0&&n[0].time-r.now()<=0;)n.shift().notification.observe(i);if(n.length>0){var o=Math.max(0,n[0].time-r.now());this.schedule(e,o)}else this.unsubscribe(),t.active=!1},t.prototype._schedule=function(e){this.active=!0,this.add(e.schedule(t.dispatch,this.delay,{source:this,destination:this.destination,scheduler:e}))},t.prototype.scheduleNotification=function(e){if(!0!==this.errored){var t=this.scheduler,n=new Zo(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(Ct.Notification.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e)},t.prototype._complete=function(){this.scheduleNotification(Ct.Notification.createComplete())},t}(ve.Subscriber),Zo=function(e,t){this.time=e,this.notification=t},es={delay:Ko};var ts={delay:function(e,t){return void 0===t&&(t=Rn.async),es.delay(e,t)(this)}};Oe.Observable.prototype.delay=ts.delay;var ns=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var rs=function(e,t){return t?function(n){return new ss(n,t).lift(new is(e))}:function(t){return t.lift(new is(e))}},is=function(){function e(e){this.delayDurationSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new os(e,this.delayDurationSelector))},e}(),os=function(e){function t(t,n){e.call(this,t),this.delayDurationSelector=n,this.completed=!1,this.delayNotifierSubscriptions=[],this.values=[]}return ns(t,e),t.prototype.notifyNext=function(e,t,n,r,i){this.destination.next(e),this.removeSubscription(i),this.tryComplete()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype.notifyComplete=function(e){var t=this.removeSubscription(e);t&&this.destination.next(t),this.tryComplete()},t.prototype._next=function(e){try{var t=this.delayDurationSelector(e);t&&this.tryDelay(t,e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.completed=!0,this.tryComplete()},t.prototype.removeSubscription=function(e){e.unsubscribe();var t=this.delayNotifierSubscriptions.indexOf(e),n=null;return-1!==t&&(n=this.values[t],this.delayNotifierSubscriptions.splice(t,1),this.values.splice(t,1)),n},t.prototype.tryDelay=function(e,t){var n=st.subscribeToResult(this,e,t);n&&!n.closed&&(this.add(n),this.delayNotifierSubscriptions.push(n)),this.values.push(t)},t.prototype.tryComplete=function(){this.completed&&0===this.delayNotifierSubscriptions.length&&this.destination.complete()},t}(et.OuterSubscriber),ss=function(e){function t(t,n){e.call(this),this.source=t,this.subscriptionDelay=n}return ns(t,e),t.prototype._subscribe=function(e){this.subscriptionDelay.subscribe(new as(e,this.source))},t}(Oe.Observable),as=function(e){function t(t,n){e.call(this),this.parent=t,this.source=n,this.sourceSubscribed=!1}return ns(t,e),t.prototype._next=function(e){this.subscribeToSource()},t.prototype._error=function(e){this.unsubscribe(),this.parent.error(e)},t.prototype._complete=function(){this.subscribeToSource()},t.prototype.subscribeToSource=function(){this.sourceSubscribed||(this.sourceSubscribed=!0,this.unsubscribe(),this.source.subscribe(this.parent))},t}(ve.Subscriber),cs={delayWhen:rs};var us={delayWhen:function(e,t){return cs.delayWhen(e,t)(this)}};function ls(){return function(){function e(){this._values=[]}return e.prototype.add=function(e){this.has(e)||this._values.push(e)},e.prototype.has=function(e){return-1!==this._values.indexOf(e)},Object.defineProperty(e.prototype,"size",{get:function(){return this._values.length},enumerable:!0,configurable:!0}),e.prototype.clear=function(){this._values.length=0},e}()}Oe.Observable.prototype.delayWhen=us.delayWhen;var ps={minimalSetImpl:ls,Set:K.root.Set||ls()},fs=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var hs=function(e,t){return function(n){return n.lift(new ds(e,t))}},ds=function(){function e(e,t){this.keySelector=e,this.flushes=t}return e.prototype.call=function(e,t){return t.subscribe(new bs(e,this.keySelector,this.flushes))},e}(),bs=function(e){function t(t,n,r){e.call(this,t),this.keySelector=n,this.values=new ps.Set,r&&this.add(st.subscribeToResult(this,r))}return fs(t,e),t.prototype.notifyNext=function(e,t,n,r,i){this.values.clear()},t.prototype.notifyError=function(e,t){this._error(e)},t.prototype._next=function(e){this.keySelector?this._useKeySelector(e):this._finalizeNext(e,e)},t.prototype._useKeySelector=function(e){var t,n=this.destination;try{t=this.keySelector(e)}catch(e){return void n.error(e)}this._finalizeNext(t,e)},t.prototype._finalizeNext=function(e,t){var n=this.values;n.has(e)||(n.add(e),this.destination.next(t))},t}(et.OuterSubscriber),vs={distinct:hs,DistinctSubscriber:bs};var ms={distinct:function(e,t){return vs.distinct(e,t)(this)}};Oe.Observable.prototype.distinct=ms.distinct;var ys=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var gs=function(e,t){return function(n){return n.lift(new _s(e,t))}},_s=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new ws(e,this.compare,this.keySelector))},e}(),ws=function(e){function t(t,n,r){e.call(this,t),this.keySelector=r,this.hasKey=!1,"function"==typeof n&&(this.compare=n)}return ys(t,e),t.prototype.compare=function(e,t){return e===t},t.prototype._next=function(e){var t=e;if(this.keySelector&&(t=re.tryCatch(this.keySelector)(e))===te.errorObject)return this.destination.error(te.errorObject.e);var n=!1;if(this.hasKey){if((n=re.tryCatch(this.compare)(this.key,t))===te.errorObject)return this.destination.error(te.errorObject.e)}else this.hasKey=!0;!1===Boolean(n)&&(this.key=t,this.destination.next(e))},t}(ve.Subscriber),Es={distinctUntilChanged:gs};var Os={distinctUntilChanged:function(e,t){return Es.distinctUntilChanged(e,t)(this)}};Oe.Observable.prototype.distinctUntilChanged=Os.distinctUntilChanged;var Ss={distinctUntilKeyChanged:function(e,t){return Es.distinctUntilChanged((function(n,r){return t?t(n[e],r[e]):n[e]===r[e]}))}};var Ts={distinctUntilKeyChanged:function(e,t){return Ss.distinctUntilKeyChanged(e,t)(this)}};Oe.Observable.prototype.distinctUntilKeyChanged=Ts.distinctUntilKeyChanged;var ks=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var xs=function(e,t,n){return function(r){return r.lift(new As(e,t,n))}},As=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new Is(e,this.nextOrObserver,this.error,this.complete))},e}(),Is=function(e){function t(t,n,r,i){e.call(this,t);var o=new ve.Subscriber(n,r,i);o.syncErrorThrowable=!0,this.add(o),this.safeSubscriber=o}return ks(t,e),t.prototype._next=function(e){var t=this.safeSubscriber;t.next(e),t.syncErrorThrown?this.destination.error(t.syncErrorValue):this.destination.next(e)},t.prototype._error=function(e){var t=this.safeSubscriber;t.error(e),t.syncErrorThrown?this.destination.error(t.syncErrorValue):this.destination.error(e)},t.prototype._complete=function(){var e=this.safeSubscriber;e.complete(),e.syncErrorThrown?this.destination.error(e.syncErrorValue):this.destination.complete()},t}(ve.Subscriber),Ns={tap:xs};var Cs={_do:function(e,t,n){return Ns.tap(e,t,n)(this)}};Oe.Observable.prototype.do=Cs._do,Oe.Observable.prototype._do=Cs._do;var Rs=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Ps=function(){return function(e){return e.lift(new Ms)}},Ms=function(){function e(){}return e.prototype.call=function(e,t){return t.subscribe(new js(e))},e}(),js=function(e){function t(t){e.call(this,t),this.hasCompleted=!1,this.hasSubscription=!1}return Rs(t,e),t.prototype._next=function(e){this.hasSubscription||(this.hasSubscription=!0,this.add(st.subscribeToResult(this,e)))},t.prototype._complete=function(){this.hasCompleted=!0,this.hasSubscription||this.destination.complete()},t.prototype.notifyComplete=function(e){this.remove(e),this.hasSubscription=!1,this.hasCompleted&&this.destination.complete()},t}(et.OuterSubscriber),Ls={exhaust:Ps};var qs={exhaust:function(){return Ls.exhaust()(this)}};Oe.Observable.prototype.exhaust=qs.exhaust;var Us=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Ds=function(e,t){return function(n){return n.lift(new Vs(e,t))}},Vs=function(){function e(e,t){this.project=e,this.resultSelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Fs(e,this.project,this.resultSelector))},e}(),Fs=function(e){function t(t,n,r){e.call(this,t),this.project=n,this.resultSelector=r,this.hasSubscription=!1,this.hasCompleted=!1,this.index=0}return Us(t,e),t.prototype._next=function(e){this.hasSubscription||this.tryNext(e)},t.prototype.tryNext=function(e){var t=this.index++,n=this.destination;try{var r=this.project(e,t);this.hasSubscription=!0,this.add(st.subscribeToResult(this,r,e,t))}catch(e){n.error(e)}},t.prototype._complete=function(){this.hasCompleted=!0,this.hasSubscription||this.destination.complete()},t.prototype.notifyNext=function(e,t,n,r,i){var o=this.resultSelector,s=this.destination;o?this.trySelectResult(e,t,n,r):s.next(t)},t.prototype.trySelectResult=function(e,t,n,r){var i=this.resultSelector,o=this.destination;try{var s=i(e,t,n,r);o.next(s)}catch(e){o.error(e)}},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(e){this.remove(e),this.hasSubscription=!1,this.hasCompleted&&this.destination.complete()},t}(et.OuterSubscriber),Bs={exhaustMap:Ds};var Hs={exhaustMap:function(e,t){return Bs.exhaustMap(e,t)(this)}};Oe.Observable.prototype.exhaustMap=Hs.exhaustMap;var Ws=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Gs=function(e,t,n){return void 0===t&&(t=Number.POSITIVE_INFINITY),void 0===n&&(n=void 0),t=(t||0)<1?Number.POSITIVE_INFINITY:t,function(r){return r.lift(new zs(e,t,n))}},zs=function(){function e(e,t,n){this.project=e,this.concurrent=t,this.scheduler=n}return e.prototype.call=function(e,t){return t.subscribe(new Qs(e,this.project,this.concurrent,this.scheduler))},e}(),Js=zs,Qs=function(e){function t(t,n,r,i){e.call(this,t),this.project=n,this.concurrent=r,this.scheduler=i,this.index=0,this.active=0,this.hasCompleted=!1,r0&&this._next(t.shift()),this.hasCompleted&&0===this.active&&this.destination.complete()},t}(et.OuterSubscriber),Ys={expand:Gs,ExpandOperator:Js,ExpandSubscriber:Qs};var Ks={expand:function(e,t,n){return void 0===t&&(t=Number.POSITIVE_INFINITY),void 0===n&&(n=void 0),t=(t||0)<1?Number.POSITIVE_INFINITY:t,Ys.expand(e,t,n)(this)}};Oe.Observable.prototype.expand=Ks.expand;var Xs=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},$s={ArgumentOutOfRangeError:function(e){function t(){var t=e.call(this,"argument out of range");this.name=t.name="ArgumentOutOfRangeError",this.stack=t.stack,this.message=t.message}return Xs(t,e),t}(Error)},Zs=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var ea=function(e,t){return function(n){return n.lift(new ta(e,t))}},ta=function(){function e(e,t){if(this.index=e,this.defaultValue=t,e<0)throw new $s.ArgumentOutOfRangeError}return e.prototype.call=function(e,t){return t.subscribe(new na(e,this.index,this.defaultValue))},e}(),na=function(e){function t(t,n,r){e.call(this,t),this.index=n,this.defaultValue=r}return Zs(t,e),t.prototype._next=function(e){0==this.index--&&(this.destination.next(e),this.destination.complete())},t.prototype._complete=function(){var e=this.destination;this.index>=0&&(void 0!==this.defaultValue?e.next(this.defaultValue):e.error(new $s.ArgumentOutOfRangeError)),e.complete()},t}(ve.Subscriber),ra={elementAt:ea};var ia={elementAt:function(e,t){return ra.elementAt(e,t)(this)}};Oe.Observable.prototype.elementAt=ia.elementAt;var oa=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var sa=function(e,t){return function(n){return n.lift(new aa(e,t))}},aa=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new ca(e,this.predicate,this.thisArg))},e}(),ca=function(e){function t(t,n,r){e.call(this,t),this.predicate=n,this.thisArg=r,this.count=0}return oa(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(ve.Subscriber),ua={filter:sa};var la={filter:function(e,t){return ua.filter(e,t)(this)}};Oe.Observable.prototype.filter=la.filter;var pa=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var fa=function(e){return function(t){return t.lift(new ha(e))}},ha=function(){function e(e){this.callback=e}return e.prototype.call=function(e,t){return t.subscribe(new da(e,this.callback))},e}(),da=function(e){function t(t,n){e.call(this,t),this.add(new ce.Subscription(n))}return pa(t,e),t}(ve.Subscriber),ba={finalize:fa};var va={_finally:function(e){return ba.finalize(e)(this)}};Oe.Observable.prototype.finally=va._finally,Oe.Observable.prototype._finally=va._finally;var ma=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var ya=function(e,t){if("function"!=typeof e)throw new TypeError("predicate is not a function");return function(n){return n.lift(new ga(e,n,!1,t))}},ga=function(){function e(e,t,n,r){this.predicate=e,this.source=t,this.yieldIndex=n,this.thisArg=r}return e.prototype.call=function(e,t){return t.subscribe(new wa(e,this.predicate,this.source,this.yieldIndex,this.thisArg))},e}(),_a=ga,wa=function(e){function t(t,n,r,i,o){e.call(this,t),this.predicate=n,this.source=r,this.yieldIndex=i,this.thisArg=o,this.index=0}return ma(t,e),t.prototype.notifyComplete=function(e){var t=this.destination;t.next(e),t.complete()},t.prototype._next=function(e){var t=this.predicate,n=this.thisArg,r=this.index++;try{t.call(n||this,e,r,this.source)&&this.notifyComplete(this.yieldIndex?r:e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){this.notifyComplete(this.yieldIndex?-1:void 0)},t}(ve.Subscriber),Ea={find:ya,FindValueOperator:_a,FindValueSubscriber:wa};var Oa={find:function(e,t){return Ea.find(e,t)(this)}};Oe.Observable.prototype.find=Oa.find;var Sa={findIndex:function(e,t){return function(n){return n.lift(new Ea.FindValueOperator(e,n,!0,t))}}};var Ta={findIndex:function(e,t){return Sa.findIndex(e,t)(this)}};Oe.Observable.prototype.findIndex=Ta.findIndex;var ka=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},xa={EmptyError:function(e){function t(){var t=e.call(this,"no elements in sequence");this.name=t.name="EmptyError",this.stack=t.stack,this.message=t.message}return ka(t,e),t}(Error)},Aa=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Ia=function(e,t,n){return function(r){return r.lift(new Na(e,t,n,r))}},Na=function(){function e(e,t,n,r){this.predicate=e,this.resultSelector=t,this.defaultValue=n,this.source=r}return e.prototype.call=function(e,t){return t.subscribe(new Ca(e,this.predicate,this.resultSelector,this.defaultValue,this.source))},e}(),Ca=function(e){function t(t,n,r,i,o){e.call(this,t),this.predicate=n,this.resultSelector=r,this.defaultValue=i,this.source=o,this.index=0,this.hasCompleted=!1,this._emitted=!1}return Aa(t,e),t.prototype._next=function(e){var t=this.index++;this.predicate?this._tryPredicate(e,t):this._emit(e,t)},t.prototype._tryPredicate=function(e,t){var n;try{n=this.predicate(e,t,this.source)}catch(e){return void this.destination.error(e)}n&&this._emit(e,t)},t.prototype._emit=function(e,t){this.resultSelector?this._tryResultSelector(e,t):this._emitFinal(e)},t.prototype._tryResultSelector=function(e,t){var n;try{n=this.resultSelector(e,t)}catch(e){return void this.destination.error(e)}this._emitFinal(n)},t.prototype._emitFinal=function(e){var t=this.destination;this._emitted||(this._emitted=!0,t.next(e),t.complete(),this.hasCompleted=!0)},t.prototype._complete=function(){var e=this.destination;this.hasCompleted||void 0===this.defaultValue?this.hasCompleted||e.error(new xa.EmptyError):(e.next(this.defaultValue),e.complete())},t}(ve.Subscriber),Ra={first:Ia};var Pa={first:function(e,t,n){return Ra.first(e,t,n)(this)}};Oe.Observable.prototype.first=Pa.first;var Ma={MapPolyfill:function(){function e(){this.size=0,this._values=[],this._keys=[]}return e.prototype.get=function(e){var t=this._keys.indexOf(e);return-1===t?void 0:this._values[t]},e.prototype.set=function(e,t){var n=this._keys.indexOf(e);return-1===n?(this._keys.push(e),this._values.push(t),this.size++):this._values[n]=t,this},e.prototype.delete=function(e){var t=this._keys.indexOf(e);return-1!==t&&(this._values.splice(t,1),this._keys.splice(t,1),this.size--,!0)},e.prototype.clear=function(){this._keys.length=0,this._values.length=0,this.size=0},e.prototype.forEach=function(e,t){for(var n=0;n=2&&(n=!0),function(r){return r.lift(new Fc(e,t,n))}},Fc=function(){function e(e,t,n){void 0===n&&(n=!1),this.accumulator=e,this.seed=t,this.hasSeed=n}return e.prototype.call=function(e,t){return t.subscribe(new Bc(e,this.accumulator,this.seed,this.hasSeed))},e}(),Bc=function(e){function t(t,n,r,i){e.call(this,t),this.accumulator=n,this._seed=r,this.hasSeed=i,this.index=0}return Dc(t,e),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(e){this.hasSeed=!0,this._seed=e},enumerable:!0,configurable:!0}),t.prototype._next=function(e){if(this.hasSeed)return this._tryNext(e);this.seed=e,this.destination.next(e)},t.prototype._tryNext=function(e){var t,n=this.index++;try{t=this.accumulator(this.seed,e,n)}catch(e){this.destination.error(e)}this.seed=t,this.destination.next(t)},t}(ve.Subscriber),Hc={scan:Vc},Wc=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Gc=function(e){return function(t){return 0===e?new Ke.EmptyObservable:t.lift(new zc(e))}},zc=function(){function e(e){if(this.total=e,this.total<0)throw new $s.ArgumentOutOfRangeError}return e.prototype.call=function(e,t){return t.subscribe(new Jc(e,this.total))},e}(),Jc=function(e){function t(t,n){e.call(this,t),this.total=n,this.ring=new Array,this.count=0}return Wc(t,e),t.prototype._next=function(e){var t=this.ring,n=this.total,r=this.count++;t.length0)for(var n=this.count>=this.total?this.total:this.count,r=this.ring,i=0;i=2?function(n){return we.pipe(Hc.scan(e,t),Qc.takeLast(1),Jo.defaultIfEmpty(t))(n)}:function(t){return we.pipe(Hc.scan((function(t,n,r){return e(t,n,r+1)})),Qc.takeLast(1))(t)}}};var Kc={max:function(e){var t="function"==typeof e?function(t,n){return e(t,n)>0?t:n}:function(e,t){return e>t?e:t};return Yc.reduce(t)}};var Xc={max:function(e){return Kc.max(e)(this)}};Oe.Observable.prototype.max=Xc.max;var $c={mergeStatic:qn.merge,merge:function(){for(var e=[],t=0;t0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(et.OuterSubscriber),au={mergeMapTo:ru,MergeMapToOperator:ou,MergeMapToSubscriber:su};var cu={mergeMapTo:function(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),au.mergeMapTo(e,t,n)(this)}};Oe.Observable.prototype.flatMapTo=cu.mergeMapTo,Oe.Observable.prototype.mergeMapTo=cu.mergeMapTo;var uu=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var lu=function(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),function(r){return r.lift(new pu(e,t,n))}},pu=function(){function e(e,t,n){this.accumulator=e,this.seed=t,this.concurrent=n}return e.prototype.call=function(e,t){return t.subscribe(new hu(e,this.accumulator,this.seed,this.concurrent))},e}(),fu=pu,hu=function(e){function t(t,n,r,i){e.call(this,t),this.accumulator=n,this.acc=r,this.concurrent=i,this.hasValue=!1,this.hasCompleted=!1,this.buffer=[],this.active=0,this.index=0}return uu(t,e),t.prototype._next=function(e){if(this.active0?this._next(t.shift()):0===this.active&&this.hasCompleted&&(!1===this.hasValue&&this.destination.next(this.acc),this.destination.complete())},t}(et.OuterSubscriber),du={mergeScan:lu,MergeScanOperator:fu,MergeScanSubscriber:hu};var bu={mergeScan:function(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),du.mergeScan(e,t,n)(this)}};Oe.Observable.prototype.mergeScan=bu.mergeScan;var vu={min:function(e){var t="function"==typeof e?function(t,n){return e(t,n)<0?t:n}:function(e,t){return e1)this.connection=null;else{var n=this.connection,r=e._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},t}(ve.Subscriber),Eu={refCount:gu},Ou=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},Su=function(e){function t(t,n){e.call(this),this.source=t,this.subjectFactory=n,this._refCount=0,this._isComplete=!1}return Ou(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var e=this._connection;return e||(this._isComplete=!1,(e=this._connection=new ce.Subscription).add(this.source.subscribe(new Au(this.getSubject(),this))),e.closed?(this._connection=null,e=ce.Subscription.EMPTY):this._connection=e),e},t.prototype.refCount=function(){return Eu.refCount()(this)},t}(Oe.Observable),Tu=Su,ku=Su.prototype,xu={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:ku._subscribe},_isComplete:{value:ku._isComplete,writable:!0},getSubject:{value:ku.getSubject},connect:{value:ku.connect},refCount:{value:ku.refCount}},Au=function(e){function t(t,n){e.call(this,t),this.connectable=n}return Ou(t,e),t.prototype._error=function(t){this._unsubscribe(),e.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),e.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._connection;e._refCount=0,e._subject=null,e._connection=null,t&&t.unsubscribe()}},t}(Me.SubjectSubscriber),Iu=(function(e){function t(t,n){e.call(this,t),this.connectable=n}Ou(t,e),t.prototype._unsubscribe=function(){var e=this.connectable;if(e){this.connectable=null;var t=e._refCount;if(t<=0)this.connection=null;else if(e._refCount=t-1,t>1)this.connection=null;else{var n=this.connection,r=e._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null}}(ve.Subscriber),{ConnectableObservable:Tu,connectableObservableDescriptor:xu});var Nu=function(e,t){return function(n){var r;if(r="function"==typeof e?e:function(){return e},"function"==typeof t)return n.lift(new Cu(r,t));var i=Object.create(n,Iu.connectableObservableDescriptor);return i.source=n,i.subjectFactory=r,i}},Cu=function(){function e(e,t){this.subjectFactory=e,this.selector=t}return e.prototype.call=function(e,t){var n=this.selector,r=this.subjectFactory(),i=n(r).subscribe(e);return i.add(t.subscribe(r)),i},e}(),Ru={multicast:Nu,MulticastOperator:Cu};var Pu={multicast:function(e,t){return Ru.multicast(e,t)(this)}};Oe.Observable.prototype.multicast=Pu.multicast;var Mu={observeOn:function(e,t){return void 0===t&&(t=0),Ut.observeOn(e,t)(this)}};Oe.Observable.prototype.observeOn=Mu.observeOn;var ju={onErrorResumeNext:function(){for(var e=[],t=0;t=2?Yc.reduce(e,t)(this):Yc.reduce(e)(this)}};Oe.Observable.prototype.reduce=sl.reduce;var al=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var cl=function(e){return void 0===e&&(e=-1),function(t){return 0===e?new Ke.EmptyObservable:e<0?t.lift(new ul(-1,t)):t.lift(new ul(e-1,t))}},ul=function(){function e(e,t){this.count=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new ll(e,this.count,this.source))},e}(),ll=function(e){function t(t,n,r){e.call(this,t),this.count=n,this.source=r}return al(t,e),t.prototype.complete=function(){if(!this.isStopped){var t=this.source,n=this.count;if(0===n)return e.prototype.complete.call(this);n>-1&&(this.count=n-1),t.subscribe(this._unsubscribeAndRecycle())}},t}(ve.Subscriber),pl={repeat:cl};var fl={repeat:function(e){return void 0===e&&(e=-1),pl.repeat(e)(this)}};Oe.Observable.prototype.repeat=fl.repeat;var hl=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var dl=function(e){return function(t){return t.lift(new bl(e))}},bl=function(){function e(e){this.notifier=e}return e.prototype.call=function(e,t){return t.subscribe(new vl(e,this.notifier,t))},e}(),vl=function(e){function t(t,n,r){e.call(this,t),this.notifier=n,this.source=r,this.sourceIsBeingSubscribedTo=!0}return hl(t,e),t.prototype.notifyNext=function(e,t,n,r,i){this.sourceIsBeingSubscribedTo=!0,this.source.subscribe(this)},t.prototype.notifyComplete=function(t){if(!1===this.sourceIsBeingSubscribedTo)return e.prototype.complete.call(this)},t.prototype.complete=function(){if(this.sourceIsBeingSubscribedTo=!1,!this.isStopped){if(this.retries||this.subscribeToRetries(),!this.retriesSubscription||this.retriesSubscription.closed)return e.prototype.complete.call(this);this._unsubscribeAndRecycle(),this.notifications.next()}},t.prototype._unsubscribe=function(){var e=this.notifications,t=this.retriesSubscription;e&&(e.unsubscribe(),this.notifications=null),t&&(t.unsubscribe(),this.retriesSubscription=null),this.retries=null},t.prototype._unsubscribeAndRecycle=function(){var t=this,n=t.notifications,r=t.retries,i=t.retriesSubscription;return this.notifications=null,this.retries=null,this.retriesSubscription=null,e.prototype._unsubscribeAndRecycle.call(this),this.notifications=n,this.retries=r,this.retriesSubscription=i,this},t.prototype.subscribeToRetries=function(){this.notifications=new Me.Subject;var t=re.tryCatch(this.notifier)(this.notifications);if(t===te.errorObject)return e.prototype.complete.call(this);this.retries=t,this.retriesSubscription=st.subscribeToResult(this,t)},t}(et.OuterSubscriber),ml={repeatWhen:dl};var yl={repeatWhen:function(e){return ml.repeatWhen(e)(this)}};Oe.Observable.prototype.repeatWhen=yl.repeatWhen;var gl=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var _l=function(e){return void 0===e&&(e=-1),function(t){return t.lift(new wl(e,t))}},wl=function(){function e(e,t){this.count=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new El(e,this.count,this.source))},e}(),El=function(e){function t(t,n,r){e.call(this,t),this.count=n,this.source=r}return gl(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return e.prototype.error.call(this,t);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},t}(ve.Subscriber),Ol={retry:_l};var Sl={retry:function(e){return void 0===e&&(e=-1),Ol.retry(e)(this)}};Oe.Observable.prototype.retry=Sl.retry;var Tl=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var kl=function(e){return function(t){return t.lift(new xl(e,t))}},xl=function(){function e(e,t){this.notifier=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new Al(e,this.notifier,this.source))},e}(),Al=function(e){function t(t,n,r){e.call(this,t),this.notifier=n,this.source=r}return Tl(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=this.errors,r=this.retries,i=this.retriesSubscription;if(r)this.errors=null,this.retriesSubscription=null;else{if(n=new Me.Subject,(r=re.tryCatch(this.notifier)(n))===te.errorObject)return e.prototype.error.call(this,te.errorObject.e);i=st.subscribeToResult(this,r)}this._unsubscribeAndRecycle(),this.errors=n,this.retries=r,this.retriesSubscription=i,n.next(t)}},t.prototype._unsubscribe=function(){var e=this.errors,t=this.retriesSubscription;e&&(e.unsubscribe(),this.errors=null),t&&(t.unsubscribe(),this.retriesSubscription=null),this.retries=null},t.prototype.notifyNext=function(e,t,n,r,i){var o=this,s=o.errors,a=o.retries,c=o.retriesSubscription;this.errors=null,this.retries=null,this.retriesSubscription=null,this._unsubscribeAndRecycle(),this.errors=s,this.retries=a,this.retriesSubscription=c,this.source.subscribe(this)},t}(et.OuterSubscriber),Il={retryWhen:kl};var Nl={retryWhen:function(e){return Il.retryWhen(e)(this)}};Oe.Observable.prototype.retryWhen=Nl.retryWhen;var Cl=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Rl=function(e){return function(t){return t.lift(new Pl(e))}},Pl=function(){function e(e){this.notifier=e}return e.prototype.call=function(e,t){var n=new Ml(e),r=t.subscribe(n);return r.add(st.subscribeToResult(n,this.notifier)),r},e}(),Ml=function(e){function t(){e.apply(this,arguments),this.hasValue=!1}return Cl(t,e),t.prototype._next=function(e){this.value=e,this.hasValue=!0},t.prototype.notifyNext=function(e,t,n,r,i){this.emitValue()},t.prototype.notifyComplete=function(){this.emitValue()},t.prototype.emitValue=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.value))},t}(et.OuterSubscriber),jl={sample:Rl};var Ll={sample:function(e){return jl.sample(e)(this)}};Oe.Observable.prototype.sample=Ll.sample;var ql=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Ul=function(e,t){return void 0===t&&(t=Rn.async),function(n){return n.lift(new Dl(e,t))}},Dl=function(){function e(e,t){this.period=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new Vl(e,this.period,this.scheduler))},e}(),Vl=function(e){function t(t,n,r){e.call(this,t),this.period=n,this.scheduler=r,this.hasValue=!1,this.add(r.schedule(Fl,n,{subscriber:this,period:n}))}return ql(t,e),t.prototype._next=function(e){this.lastValue=e,this.hasValue=!0},t.prototype.notifyNext=function(){this.hasValue&&(this.hasValue=!1,this.destination.next(this.lastValue))},t}(ve.Subscriber);function Fl(e){var t=e.subscriber,n=e.period;t.notifyNext(),this.schedule(e,n)}var Bl={sampleTime:Ul};var Hl={sampleTime:function(e,t){return void 0===t&&(t=Rn.async),Bl.sampleTime(e,t)(this)}};Oe.Observable.prototype.sampleTime=Hl.sampleTime;var Wl={scan:function(e,t){return arguments.length>=2?Hc.scan(e,t)(this):Hc.scan(e)(this)}};Oe.Observable.prototype.scan=Wl.scan;var Gl=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var zl=function(e,t){return function(n){return n.lift(new Jl(e,t))}},Jl=function(){function e(e,t){this.compareTo=e,this.comparor=t}return e.prototype.call=function(e,t){return t.subscribe(new Yl(e,this.compareTo,this.comparor))},e}(),Ql=Jl,Yl=function(e){function t(t,n,r){e.call(this,t),this.compareTo=n,this.comparor=r,this._a=[],this._b=[],this._oneComplete=!1,this.add(n.subscribe(new Xl(t,this)))}return Gl(t,e),t.prototype._next=function(e){this._oneComplete&&0===this._b.length?this.emit(!1):(this._a.push(e),this.checkValues())},t.prototype._complete=function(){this._oneComplete?this.emit(0===this._a.length&&0===this._b.length):this._oneComplete=!0},t.prototype.checkValues=function(){for(var e=this,t=e._a,n=e._b,r=e.comparor;t.length>0&&n.length>0;){var i=t.shift(),o=n.shift(),s=!1;r?(s=re.tryCatch(r)(i,o))===te.errorObject&&this.destination.error(te.errorObject.e):s=i===o,s||this.emit(!1)}},t.prototype.emit=function(e){var t=this.destination;t.next(e),t.complete()},t.prototype.nextB=function(e){this._oneComplete&&0===this._a.length?this.emit(!1):(this._b.push(e),this.checkValues())},t}(ve.Subscriber),Kl=Yl,Xl=function(e){function t(t,n){e.call(this,t),this.parent=n}return Gl(t,e),t.prototype._next=function(e){this.parent.nextB(e)},t.prototype._error=function(e){this.parent.error(e)},t.prototype._complete=function(){this.parent._complete()},t}(ve.Subscriber),$l={sequenceEqual:zl,SequenceEqualOperator:Ql,SequenceEqualSubscriber:Kl};var Zl={sequenceEqual:function(e,t){return $l.sequenceEqual(e,t)(this)}};function ep(){return new Me.Subject}Oe.Observable.prototype.sequenceEqual=Zl.sequenceEqual;var tp={share:function(){return function(e){return Eu.refCount()(Ru.multicast(ep)(e))}}};var np={share:function(){return tp.share()(this)}};Oe.Observable.prototype.share=np.share;var rp={shareReplay:function(e,t,n){return function(r){return r.lift(function(e,t,n){var r,i,o=0,s=!1,a=!1;return function(c){o++,r&&!s||(s=!1,r=new di.ReplaySubject(e,t,n),i=c.subscribe({next:function(e){r.next(e)},error:function(e){s=!0,r.error(e)},complete:function(){a=!0,r.complete()}}));var u=r.subscribe(this);return function(){o--,u.unsubscribe(),i&&0===o&&a&&i.unsubscribe()}}}(e,t,n))}}};var ip={shareReplay:function(e,t,n){return rp.shareReplay(e,t,n)(this)}};Oe.Observable.prototype.shareReplay=ip.shareReplay;var op=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var sp=function(e){return function(t){return t.lift(new ap(e,t))}},ap=function(){function e(e,t){this.predicate=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new cp(e,this.predicate,this.source))},e}(),cp=function(e){function t(t,n,r){e.call(this,t),this.predicate=n,this.source=r,this.seenValue=!1,this.index=0}return op(t,e),t.prototype.applySingleValue=function(e){this.seenValue?this.destination.error("Sequence contains more than one element"):(this.seenValue=!0,this.singleValue=e)},t.prototype._next=function(e){var t=this.index++;this.predicate?this.tryNext(e,t):this.applySingleValue(e)},t.prototype.tryNext=function(e,t){try{this.predicate(e,t,this.source)&&this.applySingleValue(e)}catch(e){this.destination.error(e)}},t.prototype._complete=function(){var e=this.destination;this.index>0?(e.next(this.seenValue?this.singleValue:void 0),e.complete()):e.error(new xa.EmptyError)},t}(ve.Subscriber),up={single:sp};var lp={single:function(e){return up.single(e)(this)}};Oe.Observable.prototype.single=lp.single;var pp=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var fp=function(e){return function(t){return t.lift(new hp(e))}},hp=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new dp(e,this.total))},e}(),dp=function(e){function t(t,n){e.call(this,t),this.total=n,this.count=0}return pp(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(ve.Subscriber),bp={skip:fp};var vp={skip:function(e){return bp.skip(e)(this)}};Oe.Observable.prototype.skip=vp.skip;var mp=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var yp=function(e){return function(t){return t.lift(new gp(e))}},gp=function(){function e(e){if(this._skipCount=e,this._skipCount<0)throw new $s.ArgumentOutOfRangeError}return e.prototype.call=function(e,t){return 0===this._skipCount?t.subscribe(new ve.Subscriber(e)):t.subscribe(new _p(e,this._skipCount))},e}(),_p=function(e){function t(t,n){e.call(this,t),this._skipCount=n,this._count=0,this._ring=new Array(n)}return mp(t,e),t.prototype._next=function(e){var t=this._skipCount,n=this._count++;if(n1?$t.concat(new $e.ArrayObservable(e,n),t):$t.concat(new Ke.EmptyObservable(n),t)}}};var Lp={startWith:function(){for(var e=[],t=0;t0?e.prototype.requestAsyncId.call(this,t,n,r):(t.actions.push(this),t.scheduled||(t.scheduled=Up.Immediate.setImmediate(t.flush.bind(t,null))))},t.prototype.recycleAsyncId=function(t,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return e.prototype.recycleAsyncId.call(this,t,n,r);0===t.actions.length&&(Up.Immediate.clearImmediate(n),t.scheduled=void 0)},t}(An.AsyncAction)},Fp=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},Bp={asap:new({AsapScheduler:function(e){function t(){e.apply(this,arguments)}return Fp(t,e),t.prototype.flush=function(e){this.active=!0,this.scheduled=void 0;var t,n=this.actions,r=-1,i=n.length;e=e||n.shift();do{if(t=e.execute(e.state,e.delay))break}while(++r0?this.startWindowEvery:this.windowSize,n=this.destination,r=this.windowSize,i=this.windows,o=i.length,s=0;s=0&&a%t==0&&!this.closed&&i.shift().complete(),++this.count%t==0&&!this.closed){var c=new Me.Subject;i.push(c),n.next(c)}},t.prototype._error=function(e){var t=this.windows;if(t)for(;t.length>0&&!this.closed;)t.shift().error(e);this.destination.error(e)},t.prototype._complete=function(){var e=this.windows;if(e)for(;e.length>0&&!this.closed;)e.shift().complete();this.destination.complete()},t.prototype._unsubscribe=function(){this.count=0,this.windows=null},t}(ve.Subscriber),Oh={windowCount:_h};var Sh={windowCount:function(e,t){return void 0===t&&(t=0),Oh.windowCount(e,t)(this)}};Oe.Observable.prototype.windowCount=Sh.windowCount;var Th=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var kh=function(e){var t=Rn.async,n=null,r=Number.POSITIVE_INFINITY;return ze.isScheduler(arguments[3])&&(t=arguments[3]),ze.isScheduler(arguments[2])?t=arguments[2]:Sn.isNumeric(arguments[2])&&(r=arguments[2]),ze.isScheduler(arguments[1])?t=arguments[1]:Sn.isNumeric(arguments[1])&&(n=arguments[1]),function(i){return i.lift(new xh(e,n,r,t))}},xh=function(){function e(e,t,n,r){this.windowTimeSpan=e,this.windowCreationInterval=t,this.maxWindowSize=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new Ih(e,this.windowTimeSpan,this.windowCreationInterval,this.maxWindowSize,this.scheduler))},e}(),Ah=function(e){function t(){e.apply(this,arguments),this._numberOfNextedValues=0}return Th(t,e),t.prototype.next=function(t){this._numberOfNextedValues++,e.prototype.next.call(this,t)},Object.defineProperty(t.prototype,"numberOfNextedValues",{get:function(){return this._numberOfNextedValues},enumerable:!0,configurable:!0}),t}(Me.Subject),Ih=function(e){function t(t,n,r,i,o){e.call(this,t),this.destination=t,this.windowTimeSpan=n,this.windowCreationInterval=r,this.maxWindowSize=i,this.scheduler=o,this.windows=[];var s=this.openWindow();if(null!==r&&r>=0){var a={subscriber:this,window:s,context:null},c={windowTimeSpan:n,windowCreationInterval:r,subscriber:this,scheduler:o};this.add(o.schedule(Rh,n,a)),this.add(o.schedule(Ch,r,c))}else{var u={subscriber:this,window:s,windowTimeSpan:n};this.add(o.schedule(Nh,n,u))}}return Th(t,e),t.prototype._next=function(e){for(var t=this.windows,n=t.length,r=0;r=this.maxWindowSize&&this.closeWindow(i))}},t.prototype._error=function(e){for(var t=this.windows;t.length>0;)t.shift().error(e);this.destination.error(e)},t.prototype._complete=function(){for(var e=this.windows;e.length>0;){var t=e.shift();t.closed||t.complete()}this.destination.complete()},t.prototype.openWindow=function(){var e=new Ah;return this.windows.push(e),this.destination.next(e),e},t.prototype.closeWindow=function(e){e.complete();var t=this.windows;t.splice(t.indexOf(e),1)},t}(ve.Subscriber);function Nh(e){var t=e.subscriber,n=e.windowTimeSpan,r=e.window;r&&t.closeWindow(r),e.window=t.openWindow(),this.schedule(e,n)}function Ch(e){var t=e.windowTimeSpan,n=e.subscriber,r=e.scheduler,i=e.windowCreationInterval,o=n.openWindow(),s=this,a={action:s,subscription:null},c={subscriber:n,window:o,context:a};a.subscription=r.schedule(Rh,t,c),s.add(a.subscription),s.schedule(e,i)}function Rh(e){var t=e.subscriber,n=e.window,r=e.context;r&&r.action&&r.subscription&&r.action.remove(r.subscription),t.closeWindow(n)}var Ph={windowTime:kh};var Mh={windowTime:function(e){var t=Rn.async,n=null,r=Number.POSITIVE_INFINITY;return ze.isScheduler(arguments[3])&&(t=arguments[3]),ze.isScheduler(arguments[2])?t=arguments[2]:Sn.isNumeric(arguments[2])&&(r=arguments[2]),ze.isScheduler(arguments[1])?t=arguments[1]:Sn.isNumeric(arguments[1])&&(n=arguments[1]),Ph.windowTime(e,n,r,t)(this)}};Oe.Observable.prototype.windowTime=Mh.windowTime;var jh=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)};var Lh=function(e,t){return function(n){return n.lift(new qh(e,t))}},qh=function(){function e(e,t){this.openings=e,this.closingSelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Uh(e,this.openings,this.closingSelector))},e}(),Uh=function(e){function t(t,n,r){e.call(this,t),this.openings=n,this.closingSelector=r,this.contexts=[],this.add(this.openSubscription=st.subscribeToResult(this,n,n))}return jh(t,e),t.prototype._next=function(e){var t=this.contexts;if(t)for(var n=t.length,r=0;r0){var s=o.indexOf(n);-1!==s&&o.splice(s,1)}},t.prototype.notifyComplete=function(){},t.prototype._next=function(e){if(0===this.toRespond.length){var t=[e].concat(this.values);this.project?this._tryProject(t):this.destination.next(t)}},t.prototype._tryProject=function(e){var t;try{t=this.project.apply(this,e)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(et.OuterSubscriber),Xh={withLatestFrom:Qh};var $h={withLatestFrom:function(){for(var e=[],t=0;tt.index?1:-1:e.delay>t.delay?1:-1},t}(An.AsyncAction),vd={VirtualTimeScheduler:dd,VirtualAction:bd},md=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},yd={TestScheduler:function(e){function t(t){e.call(this,vd.VirtualAction,750),this.assertDeepEqual=t,this.hotObservables=[],this.coldObservables=[],this.flushTests=[]}return md(t,e),t.prototype.createTime=function(e){var n=e.indexOf("|");if(-1===n)throw new Error('marble diagram for time should have a completion marker "|"');return n*t.frameTimeFactor},t.prototype.createColdObservable=function(e,n,r){if(-1!==e.indexOf("^"))throw new Error('cold observable cannot have subscription offset "^"');if(-1!==e.indexOf("!"))throw new Error('cold observable cannot have unsubscription marker "!"');var i=t.parseMarbles(e,n,r),o=new cd.ColdObservable(i,this);return this.coldObservables.push(o),o},t.prototype.createHotObservable=function(e,n,r){if(-1!==e.indexOf("!"))throw new Error('hot observable cannot have unsubscription marker "!"');var i=t.parseMarbles(e,n,r),o=new fd.HotObservable(i,this);return this.hotObservables.push(o),o},t.prototype.materializeInnerObservable=function(e,t){var n=this,r=[];return e.subscribe((function(e){r.push({frame:n.frame-t,notification:Ct.Notification.createNext(e)})}),(function(e){r.push({frame:n.frame-t,notification:Ct.Notification.createError(e)})}),(function(){r.push({frame:n.frame-t,notification:Ct.Notification.createComplete()})})),r},t.prototype.expectObservable=function(e,n){var r=this;void 0===n&&(n=null);var i,o=[],s={actual:o,ready:!1},a=t.parseMarblesAsSubscriptions(n).unsubscribedFrame;return this.schedule((function(){i=e.subscribe((function(e){var t=e;e instanceof Oe.Observable&&(t=r.materializeInnerObservable(t,r.frame)),o.push({frame:r.frame,notification:Ct.Notification.createNext(t)})}),(function(e){o.push({frame:r.frame,notification:Ct.Notification.createError(e)})}),(function(){o.push({frame:r.frame,notification:Ct.Notification.createComplete()})}))}),0),a!==Number.POSITIVE_INFINITY&&this.schedule((function(){return i.unsubscribe()}),a),this.flushTests.push(s),{toBe:function(e,n,r){s.ready=!0,s.expected=t.parseMarbles(e,n,r,!0)}}},t.prototype.expectSubscriptions=function(e){var n={actual:e,ready:!1};return this.flushTests.push(n),{toBe:function(e){var r="string"==typeof e?[e]:e;n.ready=!0,n.expected=r.map((function(e){return t.parseMarblesAsSubscriptions(e)}))}}},t.prototype.flush=function(){for(var t=this.hotObservables;t.length>0;)t.shift().setup();e.prototype.flush.call(this);for(var n=this.flushTests.filter((function(e){return e.ready}));n.length>0;){var r=n.shift();this.assertDeepEqual(r.actual,r.expected)}},t.parseMarblesAsSubscriptions=function(e){if("string"!=typeof e)return new nd.SubscriptionLog(Number.POSITIVE_INFINITY);for(var t=e.length,n=-1,r=Number.POSITIVE_INFINITY,i=Number.POSITIVE_INFINITY,o=0;o-1?n:s;break;case"!":if(i!==Number.POSITIVE_INFINITY)throw new Error("found a second subscription point '^' in a subscription marble diagram. There can only be one.");i=n>-1?n:s;break;default:throw new Error("there can only be '^' and '!' markers in a subscription marble diagram. Found instead '"+a+"'.")}}return i<0?new nd.SubscriptionLog(r):new nd.SubscriptionLog(r,i)},t.parseMarbles=function(e,t,n,r){if(void 0===r&&(r=!1),-1!==e.indexOf("!"))throw new Error('conventional marble diagrams cannot have the unsubscription marker "!"');for(var i=e.length,s=[],a=e.indexOf("^"),c=-1===a?0:a*-this.frameTimeFactor,u="object"!==o(t)?function(e){return e}:function(e){return r&&t[e]instanceof cd.ColdObservable?t[e].messages:t[e]},l=-1,p=0;p-1?l:f,notification:h})}return s},t}(vd.VirtualTimeScheduler)},gd=function(e){e.requestAnimationFrame?(this.cancelAnimationFrame=e.cancelAnimationFrame.bind(e),this.requestAnimationFrame=e.requestAnimationFrame.bind(e)):e.mozRequestAnimationFrame?(this.cancelAnimationFrame=e.mozCancelAnimationFrame.bind(e),this.requestAnimationFrame=e.mozRequestAnimationFrame.bind(e)):e.webkitRequestAnimationFrame?(this.cancelAnimationFrame=e.webkitCancelAnimationFrame.bind(e),this.requestAnimationFrame=e.webkitRequestAnimationFrame.bind(e)):e.msRequestAnimationFrame?(this.cancelAnimationFrame=e.msCancelAnimationFrame.bind(e),this.requestAnimationFrame=e.msRequestAnimationFrame.bind(e)):e.oRequestAnimationFrame?(this.cancelAnimationFrame=e.oCancelAnimationFrame.bind(e),this.requestAnimationFrame=e.oRequestAnimationFrame.bind(e)):(this.cancelAnimationFrame=e.clearTimeout.bind(e),this.requestAnimationFrame=function(t){return e.setTimeout(t,1e3/60)})},_d={RequestAnimationFrameDefinition:gd,AnimationFrame:new gd(K.root)},wd=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},Ed={AnimationFrameAction:function(e){function t(t,n){e.call(this,t,n),this.scheduler=t,this.work=n}return wd(t,e),t.prototype.requestAsyncId=function(t,n,r){return void 0===r&&(r=0),null!==r&&r>0?e.prototype.requestAsyncId.call(this,t,n,r):(t.actions.push(this),t.scheduled||(t.scheduled=_d.AnimationFrame.requestAnimationFrame(t.flush.bind(t,null))))},t.prototype.recycleAsyncId=function(t,n,r){if(void 0===r&&(r=0),null!==r&&r>0||null===r&&this.delay>0)return e.prototype.recycleAsyncId.call(this,t,n,r);0===t.actions.length&&(_d.AnimationFrame.cancelAnimationFrame(n),t.scheduled=void 0)},t}(An.AsyncAction)},Od=O&&O.__extends||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);function r(){this.constructor=e}e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},Sd={animationFrame:new({AnimationFrameScheduler:function(e){function t(){e.apply(this,arguments)}return Od(t,e),t.prototype.flush=function(e){this.active=!0,this.scheduled=void 0;var t,n=this.actions,r=-1,i=n.length;e=e||n.shift();do{if(t=e.execute(e.state,e.delay))break}while(++r0&&void 0!==arguments[0]?arguments[0]:{},t=e.publishInterval,n=void 0===t?3e3:t,r=e.maximumBatchSize,i=void 0===r?50:r,o=e.maximumBufferSize,s=void 0===o?1e3:o,a=e.maximumConsecutiveRetries,c=void 0===a?10:a,u=e.transports,l=void 0===u?[]:u,p=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.position;void 0===n&&(n=l.length),l.splice(n,0,e)},f={},h={},d=function e(t){var n=t.transports,r=t.payload;return 0===n.length?Promise.reject():n[0].process({payload:r}).catch((function(){return e({payload:r,transports:n.slice(1)})}))},b=function(e){return 0===Object.keys(e).length||V(e).every((function(e){return 0===e.length}))},v=function(){var e={};return Object.keys(f).forEach((function(t){e[t]=f[t].splice(0,i)})),b(e)?Promise.resolve():d({transports:l,payload:e}).then((function(){return Object.keys(h).forEach((function(e){return h[e]=0})),Promise.resolve()})).catch((function(){return Object.keys(e).forEach((function(t){h[t]++,h[t]1&&void 0!==arguments[1]?arguments[1]:0;return-1!==D.indexOf(M(e))?e:"function"==typeof e?"":e instanceof Error?T(e):Array.isArray(e)?O(e,t):S(e,t)},x=function(e){return function(){if(E()){var t=h[e]||h.log;t.apply(t,arguments)}var n=Array.prototype.slice.call(arguments).map((function(e){return k(e,0)})).filter((function(e){return void 0!==e})),r=q(o);r=L(r,{level:e,attributes:n,timestamp:a()}),"error"===e?r=L(r,{breadcrumbs:_.list}):_.add(r),w(r)}},A=function(e){return e.filter((function(e){return e instanceof Error}))[0]};this.debug=x("debug"),this.log=x("info"),this.info=x("info"),this.warn=x("warn"),this.error=function(){var e=Array.prototype.slice.call(arguments),t=A(e);if(!t||!t._acked)return"string"!=typeof e[0]||t||(e[0]=new Error(e[0])),x("error").apply(null,e)},this.withTags=function(t){return new e(L(n[0],{tags:L(o,t)}))},this.enableLiveLogs=function(){return b[m]="1"}}({publisher:em,tags:{actor:"visitor",site_id:sm.siteId,visitor_id:function(){return Jv()},tab_id:function(){return sm.tabId},user_agent:window.navigator.userAgent,url:function(){return String(window.location)},client_version:function(e){e||(e="visitor/bootstrapper-ea662fcc3.js");var t=e.split("-")[1];if(t)return t.slice(0,-3)}()}});var tm,nm=sm.logger,rm=new G(new function e(t){var n=t.publisher,r=t.globalTags,i=void 0===r?[]:r,o=function(e){return n.addToBucket("stats",e)},s=function(e,t,n,r){return r||(r=[]),{stat:e,params:[t,n,i.concat(r)]}};this.increment=function(e,t,n){isNaN(parseInt(t))&&(n=t,t=1),o(s("increment",e,t,n))},this.decrement=function(e,t,n){isNaN(parseInt(t))&&(n=t,t=1),o(s("decrement",e,t,n))},this.gauge=function(e,t,n){o(s("gauge",e,t,n))},this.histogram=function(e,t,n){o(s("histogram",e,t,n))},this.timing=function(e,t,n){o(s("timing",e,t,n))},this.set=function(e,t,n){o(s("set",e,t,n))},this.withTags=function(t){return new e({publisher:n,globalTags:i.concat(t)})}}({publisher:em,globalTags:["application:visitor","visitor_page_adaption:".concat(sm.conf.engagement.visitor_page_adaption),"site_id:".concat(sm.siteId)]}),(tm={},{record:function(e){tm[e]=Number(new Date)},currentLatencyFrom:function(e){var t=tm[e];return t?Number(new Date)-t:-1}})),im="sm.app.visitor_api.dynamic_import",om="https://libs.salemove.com/medra-5.4.3.min.js",am="default"===sm.conf.communications.lib,cm=am?om:sm.conf.communications.lib,um=sm.conf.integrities_enabled?om:"https://libs.salemove.com/medra-5.4.3-twilio-v2.min.js",lm=am?um:sm.conf.communications.lib,pm=function(e){return-1!==sm.conf.assets.server.indexOf("libs.")?"".concat(sm.conf.assets.server,"/").concat(e):[sm.conf.assets.server,sm.conf.assets.prepend||"/",e].join("")},fm={Medra:{url:cm,returning:function(){return sm.Medra},integrity:am?R({name:"medra"}):null},MedraTwilioV2:{url:lm,returning:function(){return sm.Medra},integrity:am?R({name:"medra"}):null},Comms:{url:pm("visitor_app/comms/app-ea662fcc3.js"),integrity:R({name:"comms"})},Cobra:{url:"".concat(sm.conf.cobra.lib.visitor,".js"),returning:function(){return sm.Cobra},integrity:R({name:"visitor_cobra"})},webcomponents:{url:pm("visitor/webcomponents-ea662fcc3.js"),integrity:R({name:"webcomponents"})},webcomponents_es5:{url:pm("visitor/webcomponents_es5-ea662fcc3.js"),integrity:R({name:"webcomponents_es5"})},legacy_webcomponents:{url:pm("visitor/legacy_webcomponents-ea662fcc3.js"),integrity:R({name:"legacy_webcomponents"})}},hm={},dm=function(e){var t,n=fm,r=P,i=rm,o=hm;"string"==typeof e?t=e:(t=e.target,e.loader&&(r=e.loader),e.possibleTargets&&(n=e.possibleTargets),e.stats&&(i=e.stats),e.loaded&&(o=e.loaded));var s=n[t];if(!s)return Gv.Observable.throw("Invalid target");if(o[t]){if(s.returning){var a=s.returning();return void 0===a?Gv.Observable.throw(new Error("An error occurred while loading ".concat(t,", as it is undefined"))):Gv.Observable.of(a)}return Gv.Observable.of(null)}return Gv.Observable.create((function(e){r({fileUrl:s.url,integrity:s.integrity,onAttempt:function(){i.increment(im,["action:attempted","module:".concat(t)])},onLoad:function(){if(o[t]=!0,s.returning){var n=s.returning();void 0===n?(i.increment(im,["action:failed","module:".concat(t)]),e.error(new Error("An error occurred while loading ".concat(t,", as it is undefined")))):(i.increment(im,["action:succeeded","module:".concat(t)]),e.next(n),e.complete())}else i.increment(im,["action:succeeded","module:".concat(t)]),e.next(),e.complete()},onError:function(){i.increment(im,["action:warning","module:".concat(t)])},onGiveUp:function(){i.increment(im,["action:failed","module:".concat(t)]);var n=new Error("Loading ".concat(t," failed"));nm.warn(n,{target:t}),n._acked=!0,e.error(n)},retryLimit:3,backoffDelay:500})}))},bm={MSG:{PROACTIVE_REQUEST:"proactive_call:request",PROACTIVE_ACCEPT:"proactive_call:accept",PROACTIVE_DECLINE:"proactive_call:decline",REACTIVE_ENGAGEMENT_REQUEST_TIMEOUT:"reactive_engagement_request_timeout",ENGAGEMENT_PREPARE:"engagement:prepare",ENGAGEMENT_CLEANUP:"engagement:cleanup",DISCONNECT:"connection_lost",RECONNECTED:"connection_restored",MEDIA_SELECTED:"media_selected",ENGAGEMENT_TRANSFERRED:"engagement:transferred",ENGAGEMENT_END_POPUP_CLOSED:"engagement:end:popup:closed",PUBLIC:{ENGAGEMENT_START:"sm:engagement:start",ENGAGEMENT_END:"sm:engagement:end",ENGAGEMENT_GET_AUDIO_TYPE:"sm:engagement:get_audio_type",ENGAGEMENT_GET_UPGRADE_MEDIA_TYPE:"sm:engagement:get_upgrade_media_type",ENGAGEMENT_MEDIA_UPGRADE_REQUEST:"sm:engagement:media_upgrade_request",ENGAGEMENT_SELECT_MEDIA_TYPE:"sm:engagement:select_media_type"},WILL_ASK_MEDIA_PERMISSION:"engagement:media_permission:will_ask",SHOW_PERMISSION_ARROW:"communication:show_permission_arrow",HIDE_PERMISSION_ARROW:"communication:hide_permission_arrow",ALLOW_STREAM:"engagement:media_permission:allow",DENY_STREAM:"engagement:media_permission:_deny",IS_ENGAGED:"engagement:is_engaged",PHONE_STATUSES:{CONNECTED:"connected",CONNECTING:"connecting"},ENGAGEMENT_REMOVE_AUDIO:"engagement:remove_audio"}},vm=new Gv.Subject;bm.vent={trigger:function(e,t){vm.next({eventName:e,eventBody:t})},observable:function(e){return vm.filter((function(t){return t.eventName===e})).map((function(e){return e.eventBody}))}};var mm={};bm.request=function(e,t){var n=mm[e];if(n)return n(t)},bm.reqres={setHandler:function(e,t){mm[e]=t},removeHandler:function(e){delete mm[e]}};var ym=[],gm=null,_m=function(){(gm=document.createElement("SPAN")).id="cobrowsing-mouse-container",document.body.appendChild(gm);var e=new MutationObserver((function(){var e,t,n=document.body.childNodes[document.body.childNodes.length-1];n!==gm&&-1===ym.indexOf(n)&&(e=document.body,(t=e.childNodes[e.childNodes.length-1])!==gm&&(ym.push(t),setTimeout((function(){ym=[]}),1e4),e.appendChild(gm)))}));return e.observe(document.body,{childList:!0}),{unsubscribe:function(){e.disconnect()}}},wm=function(){function e(t){var n=t.duration;s(this,e),this.duration=n}return c(e,[{key:"perform",value:function(){bm.vent.trigger("trigger_expand_reactive",{duration:this.duration})}}]),e}(),Em=function(){function e(t){var n=t.text,r=t.no_operators_online_text,i=t.duration,o=t.priority;s(this,e),this.text=n,this.noOperatorsOnlineText=r,this.duration=i,this.priority=o}return c(e,[{key:"perform",value:function(){bm.vent.trigger("trigger_reactive_callout",{text:this.text,noOperatorsOnlineText:this.noOperatorsOnlineText,duration:this.duration,priority:this.priority})}}]),e}(),Om=function(){function e(t){var n=t.text;s(this,e),this.text=n}return c(e,[{key:"perform",value:function(){bm.vent.trigger("trigger_media_selection",{text:this.text,source:"callout"})}}]),e}(),Sm=function(){function e(){s(this,e)}return c(e,[{key:"perform",value:function(){bm.vent.trigger("reactive_bar:enable")}}]),e}(),Tm=function(){function e(){s(this,e)}return c(e,[{key:"perform",value:function(){bm.vent.trigger("reactive_bar:disable")}}]),e}(),km=function(){function e(t){var n=t.vertical_offset,r=t.horizontal_offset;s(this,e),this.verticalOffset=n,this.horizontalOffset=r}return c(e,[{key:"perform",value:function(){bm.vent.trigger("reactive_bar:set_position",{verticalOffset:this.verticalOffset,horizontalOffset:this.horizontalOffset})}}]),e}(),xm=function(e){var t=e.category,n=e.action,r=e.label;nm.info("Tracking Google Analytics Event",{category:t,action:n,label:r}),window._gaq&&window._gaq.push?window._gaq.push(["_trackEvent",t,n,r]):"function"==typeof window.ga&&window.ga("send","event",t,n,r)},Am=function(){function e(t){s(this,e),this.options=t}return c(e,[{key:"perform",value:function(){switch(this.options.provider){case"google":this.trackGoogle(this.options);break;case"omniture":this.trackOmniture(this.options);break;default:nm.error("Unknown analytics provider",this.options.provider)}}},{key:"trackGoogle",value:function(e){var t=e.category,n=e.action,r=e.fields;xm({category:t,action:n,label:r?JSON.stringify(r):void 0})}},{key:"trackOmniture",value:function(e){!function(e){var t=e.tagFunction,n=e.tagId,r=e.params;nm.info("Tracking Omniture Analytics Event",{tagFunction:t,tagId:n,params:r});try{"function"==typeof window[t]&&window[t](n,k.clone(r))}catch(e){nm.warn("Client error occurred during Omniture event tracking",e)}}({tagFunction:e.tag_function,tagId:e.tag_id,params:e.fields})}}]),e}(),Im=function(e,t){var n=t.operator;return n&&-1!==n.teamNames.indexOf(e)},Nm=function(){function e(t){var n=t.operator_team;s(this,e),this.operatorTeam=n}return c(e,[{key:"perform",value:function(e){e.cobraObservable.filter(k.partial(Im,this.operatorTeam)).pluck("cobraSourceInitializer").subscribe((function(e){return e.block()}))}}]),e}(),Cm=function(){function e(t){var n=t.text,r=t.duration;s(this,e),this.text=n,this.duration=r}return c(e,[{key:"perform",value:function(){bm.vent.trigger("show_engagement_invitation",{text:this.text,duration:this.duration})}}]),e}(),Rm=k.compose(k.isEmpty,k.symmetricDifference);(sm.BusinessRules={}).ACTION_TYPES={SHOW_OPERATORS_IN_SELECTOR_V2:"show_operators_in_selector_v2"};var Pm=function(e){var t=e.event,n=e.site_id,r=e.tab_id;return"business_rules"===t&&n===sm.siteId&&(!r||r===sm.tabId)},Mm=function(){function e(){s(this,e)}return c(e,[{key:"perform",value:function(){}}]),e}(),jm=function(){function e(t){s(this,e),this.expectedAction=t}return c(e,[{key:"perform",value:function(){throw new Error("No handler found for action ".concat(this.expectedAction))}}]),e}(),Lm={expand_operator_selector:wm,reactive_callout:Em,media_selection:Om,show_reactive_tab_only_when:Sm,hide_reactive_tab:Tm,set_reactive_tab_position:km,show_operators_in_selector_v2:Mm,send_analytics_event:Am,hide_page_from_operators:Nm,show_engagement_invitation:Cm},qm=new Re,Um=qm.pipe(Ib());Um.connect();var Dm=function(){function e(t){var n=t.volatileNotifications,r=t.cobraObservable,i=t.routingObservable;s(this,e),this._performAction=this._performAction.bind(this),this.cobraObservable=r,this.routingObservable=i,this.actionsObservable=Um.pipe(hb(n.pipe(eb(Pm),ub(k.prop("payload"))))),this._routingUpdateTimeout=sm.conf.overseer.routing_update_timeout_in_milliseconds}return c(e,[{key:"start",value:function(){return this.actionsObservable.subscribe(this._performAction)}},{key:"_performAction",value:function(e){var t=e.type,n=e.rule_id,r=e.browser_event_conditions,i=this.cobraObservable,o=function(e,t){var n=Lm[e];return n?new n(t):new jm(e)}(t,e);(function(e){var t=e.expectedQueueIds,n=e.routingObservable,r=e.routingUpdateTimeout,i=e.loggerMetadata,o=void 0===i?{}:i,s=e.logger,a=void 0===s?nm:s;return t?n.pipe(eb((function(e){var n=e.queue_ids;return!(!n||!t)&&Rm(n,t)})),$b(1),sv(r),Rd((function(e){return"TimeoutError"===e.name?a.warn("In-browser business rule action not triggered, expected queue ids not received",k.merge(o,{queue_ids:t})):a.error("In-browser business rule action triggering error",e),rn()}))):vt(null)})({expectedQueueIds:k.prop("queue_ids",r),routingUpdateTimeout:this._routingUpdateTimeout,routingObservable:this.routingObservable,loggerMetadata:{type:t,rule_id:n}}).subscribe((function(){var t,n;t=e,n={rule_id:k.prop("rule_id",t),action_attributes:k.omit(["rule_id"])(t)},nm.log("In-browser business rule action triggered",n),o.perform(i)}),(function(e){return nm.error("Error from should trigger in-browser action subscription",e)}))}}],[{key:"triggerAction",value:function(e){qm.next(e)}},{key:"actionTriggers",value:function(e,t){return Um.pipe(hb(e.pipe(eb(Pm),ub(k.prop("payload")))),eb((function(e){return e.type===t})))}}]),e}();sm.BusinessRules.Controller=Dm;var Vm=function(e){return{element_text:e.textContent,element_id:e.id,element_tag_name:e.tagName,element_class_name:e.className}},Fm=function(e){return!function(e){return 0===e.offsetWidth&&0===e.offsetHeight||e.style&&"none"===e.style.display}(e)},Bm=function(e){for(var t=e.parentElement,n=[];null!==t;)n.push(t),t=t.parentElement;return n},Hm=function(e){return Array.prototype.slice.call(e)},Wm=function(e,t){return(e.matches||e.msMatchesSelector).call(e,t)},Gm=1,zm=10;function Jm(e){if(!e)return null;for(var t=[];e&&e.nodeType===Gm;e=e.parentNode){for(var n=0,r=e.previousSibling;r;r=r.previousSibling)r.nodeType!==zm&&r.nodeName===e.nodeName&&++n;var i=(e.prefix?e.prefix+":":"")+e.localName,o="["+(n+1)+"]";t.splice(0,0,i+o)}return t.length?"/"+t.join("/"):null}var Qm=new RegExp(/\/([^/[]+)\[(\d+)\]/g),Ym=new RegExp(/:nth-of-type\(1\)/g);function Km(e,t){if("/"===t)return e;if(t){var n=t.replace(Qm,"$1:nth-of-type($2) > ").slice(0,-2).replace(Ym,"");return e.querySelector(n)}return null}var Xm=function(e,t){return Gv.Observable.fromEventPattern((function(n){return e.addEventListener(t,n)}),(function(n){return e.removeEventListener(t,n)}))},$m=function(e,t){return Gv.Observable.fromEventPattern((function(n){return e.on(t,n)}),(function(n){return e.off(t,n)}))},Zm=function(e){return Gv.Observable.create((function(t){var n=e.subscribe(t);return function(){return n.unsubscribe()}}))},ey=function(e){return Gv.Observable.create((function(t){var n=e.subscribe(t.next.bind(t),t.error.bind(t),t.complete.bind(t));return function(){return n.dispose()}}))},ty=function(e){return e.flatMap((function(e){return Gv.Observable.throw(e)}))},ny=function(e){return Gv.Observable.create((function(t){e.connect(),e.subscribe(t)}))},ry=function(e,t){var n=t.maxRetries,r=t.calculateDelay,i=t.shouldRetry,o=void 0===i?k.always(!0):i,s=t.scheduler,a=void 0===s?Gv.Scheduler.asap:s;return e.retryWhen((function(e){return function(e,t){return e.scan((function(e,n){return u({count:e.count+1},t,n)}),{count:0})}(e,"error").flatMap((function(e){var t=e.count,i=e.error;return o(i)&&t<=n?Gv.Observable.timer(r(t),a):Gv.Observable.throw(i)}))}))},iy=function(e){var t=e.target,n=e.selector;return"function"==typeof t.msMatchesSelector?t.msMatchesSelector(n):"function"==typeof t.matches&&t.matches(n)},oy=function(e){var t=e.pattern;return-1!==e.element.textContent.indexOf(t)},sy=function(e){return e&&e.nodeType===Gm},ay=function(e){var t=e.selector;return t&&-1!==t.indexOf(":contains")},cy=function(e){var t=e.selector,n=t.replace(/'/g,'"').match(/(.*):contains\("([^"]+)"/);if(k.isNil(n))throw new Error("Failed to match :contains selector - ".concat(t));var r=n[1].trim(),i=n[2].trim();if(k.isEmpty(r))throw new Error("The :contains selector has no tag to match");return{cssSelector:r,containsText:i}},uy=function(e){return ay({selector:e})?function(e){var t=e.selector,n=cy({selector:t}),r=n.cssSelector,i=n.containsText,o=Hm(document.querySelectorAll(r));return k.filter((function(e){return oy({pattern:i,element:e})}),o)}({selector:e}):Hm(document.querySelectorAll(e))},ly=function(e,t){return Ln.apply(void 0,_(k.map((function(t){return Xm(t,e)}),t)))},py=function(e){var t=e.elementSelector,n=e.eventName;return ly(n,uy(t))},fy=function(e){var t=e.target,n=e.selector;if(!sy(t))return!1;if(ay({selector:n})){var r=cy({selector:n}),i=r.cssSelector,o=r.containsText;return iy({target:t,selector:i})&&oy({pattern:o,element:t})}return!k.isEmpty(n)&&iy({target:t,selector:n})},hy=function(){function e(t){var n=t.id,r=t.form_selector,i=t.input_selector,o=t.value;s(this,e),this.filteredValueOrFocusout=this.filteredValueOrFocusout.bind(this),this._valueMatching=this._valueMatching.bind(this),this._formatEvent=this._formatEvent.bind(this),this.id=n,this.formSelector=r,this.inputSelector=i,this.value=o}return c(e,[{key:"track",value:function(){return Ln(this._trackTextFields(),this._trackChangeableFields(),this._trackCheckableFields()).pipe(ub(this._formatEvent))}},{key:"_trackTextFields",value:function(){var e;try{e=ly("keyup",this._getObservableFields("input[type=text], input:not([type]), textarea"))}catch(t){this._recordInvalidSelector(t),e=rn()}return e.pipe(eb(this._valueChangingKey),ub(this._extractValueFromInput),Jd(k.equals),eb(this._valueMatching),Kb(this.filteredValueOrFocusout))}},{key:"_trackChangeableFields",value:function(){var e;try{e=ly("change",this._getObservableFields("select"))}catch(t){this._recordInvalidSelector(t),e=rn()}return e.pipe(ub(this._extractValueFromOption),Jd(k.equals),eb(this._valueMatching))}},{key:"_trackCheckableFields",value:function(){var e;try{e=ly("change",this._getObservableFields("input[type=radio], input[type=checkbox]"))}catch(t){this._recordInvalidSelector(t),e=rn()}return e.pipe(ub(this._extractValueFromInput),eb(this._valueMatching))}},{key:"_getObservableFields",value:function(e){if(this.inputSelector)return Hm(document.querySelectorAll(this.inputSelector)).filter((function(t){return fy({target:t,selector:e})}));if(this.formSelector){var t=Hm(document.querySelectorAll("form"+this.formSelector));return k.unnest(k.map((function(t){return Hm(t.querySelectorAll(e))}),t))}return Hm(document.body.querySelectorAll(e))}},{key:"filteredValueOrFocusout",value:function(e){return this.value?vt(e):Xm(e.target,"focusout").pipe(lb(e))}},{key:"_valueChangingKey",value:function(e){return e.keyCode>=45}},{key:"_valueMatching",value:function(e){var t=e.target.value;return!this.value||t.match(new RegExp(this.value))}},{key:"_extractValueFromInput",value:function(e){return{target:e.target,value:e.target.value}}},{key:"_extractValueFromOption",value:function(e){var t=k.find((function(e){return e.selected}),Hm(e.target.querySelectorAll("option")));return{target:e.target,value:t&&t.value}}},{key:"_formatEvent",value:function(e){var t=e.target,n=e.value;return{id:this.id,type:"form_filling",source_attributes:k.merge(Vm(t),{value:n})}}},{key:"_recordInvalidSelector",value:function(e){rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:form_filling","reason:invalid_selector"]),nm.warn("Failed to track form filling. Invalid selector",{error:e,form_selector:this.formSelector,input_selector:this.inputSelector,source_id:this.id})}}]),e}(),dy="clicking",by=function(){function e(t){var n=t.id,r=t.element_selector,i=t.element_tag,o=t.number,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nm,c=arguments.length>2&&void 0!==arguments[2]?arguments[2]:500;s(this,e),this._isTargetElementsOrItsChild=this._isTargetElementsOrItsChild.bind(this),this._formatEvent=this._formatEvent.bind(this),this.id=n,this.elementSelector=r,this.elementTag=i,this.number=o,this.logger=a,this.throttleTime=c}return c(e,[{key:"track",value:function(){var e,t,n=this,r=(e=document,t="click",Gv.Observable.fromEventPattern((function(n){return e.addEventListener(t,n,!0)}),(function(n){return e.removeEventListener(t,n,!0)}))).pipe(eb((function(e){return n._isTargetElementsOrItsChild(e.target)}))),i=this.number||1;return function(e,t){var n=e.events,r=e.throttleTime,i=e.numberToTrigger;return n.pipe(iv(r,t),Wb(i-1))}({events:r,throttleTime:this.throttleTime,numberToTrigger:i}).map(this._formatEvent)}},{key:"_isTargetElementsOrItsChild",value:function(e){var t=this._getElementsSelector();try{var n=uy(t);return k.intersection(n,function(e){for(var t=[];e;)t.push(e),e=e.parentElement;return t}(e)).length>0}catch(e){return rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:".concat(dy),"reason:invalid_selector"]),this.logger.warn(e,"Failed to query DOM element",{elementSelector:t}),!1}}},{key:"_getElementsSelector",value:function(){return this._tagConstraint()+this._selectorConstraint()}},{key:"_tagConstraint",value:function(){return this.elementTag||""}},{key:"_selectorConstraint",value:function(){return this.elementSelector?"".concat(this.elementSelector):""}},{key:"_formatEvent",value:function(e){return{id:this.id,type:dy,source_attributes:Vm(e.target)}}}]),e}();var vy=function(){function e(t){var n=t.source_id;s(this,e),this.saveNavigationEvent=this.saveNavigationEvent.bind(this),this.clear=this.clear.bind(this),this._getHistory=this._getHistory.bind(this),this._formatHistory=this._formatHistory.bind(this),this.key="sm_navigations-"+n,this.storage=window.sessionStorage}return c(e,[{key:"saveNavigationEvent",value:function(e){this.storage.setItem(this.key,this._formatHistory(e))}},{key:"anyMatch",value:function(e){return k.any((function(t){return t.match(e)}))(this._getHistory())}},{key:"clear",value:function(){this.storage.removeItem(this.key)}},{key:"_getHistory",value:function(){try{return JSON.parse(this.storage.getItem(this.key))||[]}catch(e){return sm.logger.error("Unexpected format for navigation history in sessionStorage",{error:e}),this.clear(),[]}}},{key:"_formatHistory",value:function(e){var t=k.takeLast(2,k.append(e,this._getHistory()));return JSON.stringify(t)}}]),e}();var my=!1;try{var yy=Object.defineProperty({},"passive",{get:function(){return my=!0}});window.addEventListener("sm-passive-test",null,yy),window.removeEventListener("sm-passive-test",null,yy)}catch(e){}var gy=function(e,t){return Gv.Observable.fromEventPattern((function(n){return e.addEventListener(t,n,!!my&&{passive:!0})}),(function(n){return e.removeEventListener(t,n)}))},_y={getStream:function(e){var t,n=k.map((function(e){return gy(document,e)}),e);return Gv.Observable.merge((t=Gv.Observable).merge.apply(t,_(n)),gy(window,"focus"),gy(window,"pageshow"))}};sm.PeriodicalActivityTracker=_y;var wy=function(){var e=g(void 0!==document.hidden?["hidden","visibilitychange"]:void 0!==document.mozHidden?["mozHidden","mozvisibilitychange"]:void 0!==document.msHidden?["msHidden","msvisibilitychange"]:["webkitHidden","webkitvisibilitychange"],2),t=e[0],n=e[1];if(void 0===document.addEventListener||void 0===t)return Gv.Observable.of({focused:void 0});var r=function(){return{visible:!document[t]}};return gy(document,n).map(r).startWith(r())},Ey=function(){var e=(window.crypto||window.msCrypto).getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=191&e[8]|128;for(var t="",n=0;n-1&&(t+="-");return t},Oy=function(e){return"object"===o(e)&&Boolean(e&&e.messageName)},Sy=function(e,t,n){var r={messageName:e,payload:t};return n&&(r.options=n),r};function Ty(e){var t=this,n=new ky({allowedSource:e});["on","off","start","stop","respondTo"].forEach((function(e){t[e]=n[e].bind(n)})),this.observable=function(e){return $m(n,e)},this.emit=function(t,n,r){e.postMessage(Sy(t,n,r),"*")},this.request=function(e,n,r){var i=e+":response",o=Ey();t.on(i,(function e(n,s,a,c){c&&c.requestId===o&&(t.off(i,e),r(n,s,a))})),t.emit(e,n,{requestId:o})}}function ky(e){var t=this,n=e.allowAnySource,r=e.allowedSource;if(n&&r)throw new Error("Pass allowedSource or allowAnySource, not both");if(!n&&!r)throw new Error("Pass allowedSource or allowAnySource");var i=function(e){if((n||e.source===r)&&Oy(e.data)){var i=e.data,o=i.messageName,s=i.payload,a=i.options;return t.emitEvent(o,[s,e.source,e.origin,a])}};this.start=function(){window.addEventListener("message",i)},this.stop=function(){window.removeEventListener("message",i),t.removeEvent()},this.respondTo=function(e,n){var r=function(t,r,i,o){n(t,(function(t){return r.postMessage(Sy(e+":response",t,o),i)}),r,i)};return t.on(e,r),function(){return t.off(e,r)}}}ky.prototype=Object.create(T.prototype);var xy=null,Ay=function(){if(!xy){var e=_y.getStream(["scroll","keyup","mousemove","touchstart","orientationchange"]).share(),t=new ky({allowAnySource:!0});t.start();var n=$m(t,"activity_from_cobrowsable_iframe"),r=wy().filter(k.propEq("visible",!0));(xy=Gv.Observable.merge(e,n,r).publish()).connect()}return xy};var Iy=function(e){return e?parseFloat(e.replace(/[^\d\.]+/,"")):null},Ny="number",Cy=function(){function e(t){var n=t.id,r=t.element_selector,i=t.minimum_value;s(this,e),this._elementValues=this._elementValues.bind(this),this._numberMatching=this._numberMatching.bind(this),this._formatEvent=this._formatEvent.bind(this),this.id=n,this.elementSelector=r,this.minimumValue=i}return c(e,[{key:"track",value:function(){return Mn(100).pipe(vb(this._elementValues),eb(this._numberMatching),ub(this._formatEvent),$b(1))}},{key:"_elementValues",value:function(){var e;try{e=Hm(document.querySelectorAll(this.elementSelector))}catch(t){rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:".concat(Ny),"reason:invalid_selector"]),nm.warn("Failed to track number. Invalid selector",{error:t,element_selector:this.elementSelector,source_id:this.id}),e=[]}return Ft(k.flatten(e.map(this._elementValue)))}},{key:"_elementValue",value:function(e){return[{element:e,value:Iy(e.innerHTML)},{element:e,value:Iy(e.value)}]}},{key:"_numberMatching",value:function(e){var t=e.value;return"number"==typeof t&&t>=this.minimumValue}},{key:"_formatEvent",value:function(e){var t=e.element,n=e.value;return{id:this.id,type:Ny,source_attributes:k.merge(Vm(t),{value:n})}}}]),e}();var Ry={attributes:!0,characterData:!1,childList:!1,subtree:!1,attributeOldValue:!1,characterDataOldValue:!1};var Py={text:"chat",audio:"voice",phone:"phone",video:"video"};var My=function(){function e(){s(this,e)}return c(e,[{key:"track",value:function(){return rn()}}]),e}(),jy={form_filling:hy,clicking:by,time_on_page:function(e){var t=e.id,n=e.seconds,r=function(){return{id:t,type:"time_on_page",source_attributes:{}}};this.track=function(){return hr(1e3*n).pipe(ub(r))}},mouse_in:function(e){var t=e.id,n=e.element_selector,r=function(e){return{id:t,type:"mouse_in",source_attributes:Vm(e.target)}};this.track=function(){try{return py({elementSelector:n,eventName:"mouseenter"}).pipe(ub(r))}catch(e){return rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:mouse_in","reason:invalid_selector"]),nm.warn("Failed to track mouse in. Invalid selector",{error:(null==e?void 0:e.message)||e,element_selector:n,source_id:t}),rn()}}},mouse_out:function(e){var t=e.id,n=e.element_selector,r=function(e){return{id:t,type:"mouse_out",source_attributes:Vm(e.target)}};this.track=function(){try{return py({elementSelector:n,eventName:"mouseleave"}).pipe(ub(r))}catch(e){return rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:mouse_out","reason:invalid_selector"]),nm.warn("Failed to track mouse out. Invalid selector",{error:e,element_selector:n,source_id:t}),rn()}}},scrolling:function(e){var t=e.id,n=e.percentage,r=function(){return{id:t,type:"scrolling",source_attributes:{}}},i=function(){var e=window.pageYOffset,t=window.innerHeight;return e/(document.documentElement.scrollHeight-t)*100>n};this.track=function(){return Xm(window,"scroll").pipe(eb(i),ub(r),$b(1))}},navigation:function(e){var t=e.id,n=e.path,r=function(){return{id:t,type:"navigation",source_attributes:{}}};this.track=function(){var e=new RegExp(n,"i");return sm.hrefObservable.pipe(eb((function(t){return t.match(e)})),ub(r))}},activity:function(e){var t=e.id,n=function(){return{id:t,type:"activity",source_attributes:{}}};this.track=function(){return hr(6e4).pipe(mb(Ay()),$b(1),Rb(),ub(n))}},number:Cy,element_created:function(e){var t=e.id,n=e.element_selector,r=e.on_page_load;this.track=function(e){var i=e.options;return n?i.initialLoad&&!r?rn():vt({id:t,type:"element_created",source_attributes:{}}):rn()}},element_changed:function(e){var t=e.id,n=e.element_selector,r=function(e){return{id:t,type:"element_changed",source_attributes:Vm(e.target)}};this.track=function(e){var i=e.options,o=i.triggerObservable,s=i.mutationObserver;try{uy(n).forEach((function(e){s.observe(e,Ry)}))}catch(e){rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:element_changed","reason:invalid_selector"]),nm.warn("Failed to observe element changes. Invalid selector",{error:e,element_selector:n,source_id:t})}return o.pipe(ub(r))}},transfer:function(e){var t=e.id,n=function(e){return{id:t,type:"transfer",source_attributes:{operator_id:e.operatorId,operator_name:e.operatorName,starting_media:e.startingMedia}}};this.track=function(){return bm.vent.observable(bm.MSG.ENGAGEMENT_TRANSFERRED).pipe(ub(n))}},proactive_accept:function(e){var t=e.id,n=function(e){var n=e.operator;return{id:t,type:"proactive_accept",source_attributes:{operator_id:n.id,operator_name:n.name}}};this.track=function(){return bm.vent.observable(bm.MSG.PROACTIVE_ACCEPT).pipe(zd(k.prop("engagement_request_id")),ub(n))}},proactive_decline:function(e){var t=e.id,n=function(e){var n=e.operator;return{id:t,type:"proactive_decline",source_attributes:{operator_id:n.id,operator_name:n.name}}};this.track=function(){return bm.vent.observable(bm.MSG.PROACTIVE_DECLINE).pipe(ub(n))}},engagement_start:function(e){var t=e.id,n=function(e){var n=e.operator,r=e.startingMedia,i=e.engagementId,o=e.type;return{id:t,type:"engagement_start",source_attributes:{operator_id:n.id,operator_name:n.name,proactive_or_reactive:o,engagement_media:Py[r],engagement_id:i}}};this.track=function(){return bn(sm.getApi({version:"v1"})).pipe(vb((function(e){return e.observable(e.EVENTS.ENGAGEMENT_START)})),eb(k.complement(k.prop("isReestablishing"))),ub(n))}},reactive_engagement_request_timeout:function(e){var t=e.id,n=function(e){var n=e.operator;return{id:t,type:"reactive_engagement_request_timeout",source_attributes:{operator_id:n.id,operator_name:n.name}}};this.track=function(){return bm.vent.observable(bm.MSG.REACTIVE_ENGAGEMENT_REQUEST_TIMEOUT).pipe(ub(n))}},consecutive_navigation:function(e,t){var n=e.id,r=e.to,i=e.from,o=t||new vy({source_id:n}),s=function(){return o.anyMatch(new RegExp(i,"i"))},a=function(){return{id:n,type:"consecutive_navigation",source_attributes:{}}};this.track=function(){return sm.hrefObservable.pipe(eb((function(e){return e.match(new RegExp(i,"i"))}))).subscribe(o.saveNavigationEvent),sm.hrefObservable.pipe(eb(k.both((function(e){return e.match(new RegExp(r,"i"))}),s)),nv(o.clear),ub(a))}},enqueued:function(e){var t=e.id;this.track=function(e){var n=e.internalVisitorStateObservable,r=["enqueued","request_sent"],i=k.propEq("site_id",sm.siteId),o=k.compose(k.filter(i),k.pathOr([],["omniq","queue_tickets"])),s=k.compose(k.nth(0),k.filter((function(e){var t=k.lensPath(["visitor","browser_tab_id"]);return k.compose(k.equals(sm.tabId),k.view(t))(e)})),k.filter((function(e){return-1!==r.indexOf(e.state)})),o);return n.pipe(ub(s),eb(k.identity),Jd(null,k.prop("id")),ub((function(e){return{id:t,type:"enqueued",source_attributes:{ticket_id:e.id}}})))}}},Ly={buildObservable:k.curry((function(e,t,n){var r=function(e){var t=e.sources,n=e.internalVisitorStateObservable,r=e.options;return 0===Object.keys(t).length?rn():new(jy[t.type]||My)(t).track({internalVisitorStateObservable:n,options:r})}({sources:t.sources,internalVisitorStateObservable:e,options:n});return t.url_matcher?r.pipe(bv(function(e){var t=new RegExp(e,"i");return sm.hrefObservable.pipe(ub((function(e){return e.match(t)})),Jd(k.equals))}(t.url_matcher),(function(e,t){return{value:e,isMatching:t}})),eb(k.prop("isMatching")),ub(k.prop("value"))):r}))},qy=function(){function e(){s(this,e)}return c(e,null,[{key:"observable",value:function(e,t){var n=this._selectorsToObserveOnElementCreated(e.sources);return n.length>0?this._trackCreatedElements(e,n,t):vt({})}},{key:"_trackCreatedElements",value:function(e,t,n){var r=this._initiateSourceAttributes(e.sources);return n.pipe(ub((function(e){return{target:e,initialLoad:!1}})),Qb({target:document.body,initialLoad:!0}),eb(this._filterBySourceType({source:e.sources,selectors:t,rawRule:e})),ub(k.pick(["initialLoad"])),ub(k.merge(r)))}},{key:"_filterBySourceType",value:function(e){var t=this,n=e.source,r=e.selectors,i=e.rawRule;return function(e){var o=e.target;return!(!e.initialLoad||"element_created"===n.type)||t._targetMatchesAny(o,r,i,n)}}},{key:"_initiateSourceAttributes",value:function(e){switch(e.type){case"element_changed":return this._getElementChangedAttributes(e);default:return{}}}},{key:"_getElementChangedAttributes",value:function(e){var t=new Re,n=new MutationObserver((function(n){return k.forEach((function(n){if(fy({target:n.target,selector:e.desired_selector}))return t.next(n)}),n)}));return{triggerObservable:t.asObservable(),mutationObserver:n}}},{key:"_selectorsToObserveOnElementCreated",value:function(e){switch(e.type){case"form_filling":return[e.form_selector,e.input_selector];case"mouse_in":case"mouse_out":case"element_changed":case"element_created":return[e.element_selector];default:return[]}}},{key:"_targetMatchesAny",value:function(e,t,n,r){return k.any((function(t){try{return fy({target:e,selector:t})||function(e){var t=e.target,n=e.selector;return!(!sy(t)||!t.hasChildNodes())&&k.any((function e(t){var r=fy({target:t,selector:n});return!r&&t.hasChildNodes()?k.any(e,t.childNodes):r}),t.childNodes)}({target:e,selector:t})}catch(e){return rm.increment("sm.app.visitor.business_rules.tracker",["action:failed","type:".concat(r.type),"reason:invalid_selector"]),nm.warn("Failed to track element. Invalid selector",{error:e&&e.message,selector:t,source_type:r.type,rule_id:n.id}),!1}}),t)}}]),e}();function Uy(e){return(Uy="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Dy(e){return function(e){if(Array.isArray(e))return Vy(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return Vy(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Vy(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Vy(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&void 0!==arguments[0]?arguments[0]:{};(s(this,e),this.cause=n.cause,n.message&&(this.message=n.message),this.cause&&k.contains(this.cause,sg))||(this.cause=Ky.SALEMOVE.INTERNAL_ERROR,(t=sm.logger).error.apply(t,["Incorrect Error usage"].concat(Array.prototype.slice.call(arguments))))},cg=function(e){var t=String(e);if(0===t.indexOf("[object "))try{t=JSON.stringify(e)}catch(e){t=e instanceof TypeError?"Unable to parse param: ".concat(e.message):"Unexpected parse error ".concat(e)}return t},ug=function(e,t){t||(t={});var n,r=t.logger||nm;return n=e.cause,k.contains(n,k.values(Ky.SALEMOVE))?e:function(e,t){if(e||(e={}),t||(t=nm),k.contains(e.status,Zy))return new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR});if(0===e.status||0===e.readyState)return new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT});var n="Uncaught error in 'public' observable. Wrapping as an internal error.";return e.details&&(n+=" Details: ".concat(cg(e.details),".")),e.error&&(n+=" Error: ".concat(cg(e.error),".")),e.debug_message&&(n+=" Debug message: ".concat(cg(e.debug_message),".")),e.message&&(n+=" Message: ".concat(cg(e.message))),t.error(n.substr(0,1e3),e),new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR})}(e,r)},lg=function(e){return e||(e={}),Gv.Observable.throw(ug(e))},pg=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e instanceof ag)return Gv.Observable.throw(e);var n=function(){return k.contains(e.status,eg)?new ag({cause:Ky.SALEMOVE.INVALID_INPUT}):409===e.status?new ag({cause:Ky.SALEMOVE.CONFLICT}):e.cause===Ky.SALEMOVE.NETWORK_TIMEOUT?e:ug(e)},r=n();return t.allowedCauses&&r.cause!==Ky.SALEMOVE.INTERNAL_ERROR&&!k.contains(r.cause,t.allowedCauses)?(nm.error("Unhandled error treated as internal error",{status:e.status,message:e.message,debug_message:e.debugMessage}),Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR}))):Gv.Observable.throw(r)},fg=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,hg=function(e,t,n,r){var i=function(e){if(!e.match(fg))throw Error("Invalid visitor ID format");var t=e.split("-")[0];return parseInt(t,16)%100}(r),o=k.path([t,n],e);if(k.isNil(o))throw Error("Feature toggle value is absent");var s=k.type(o);if(!k.any(k.equals(s),["String","Number"]))throw Error("Invalid feature toggle type: ".concat(s,". Required type: String or Number"));var a=parseInt(o,10);if(isNaN(a))throw Error("Invalid feature toggle value. Value must be a number");if(a<0||a>100)throw Error("Invalid feature toggle value. Value must be within [0, 100] range");return a>i};function dg(e,t,n,r){var i=!1;return{enabledForVisitor:function(o){return s=function(){try{return hg(e,n,r,o)}catch(e){return nm.error("Failed to check feature toggle",{error:e,namespace:n,feature:r}),!1}},a="sm.app.".concat(n,".features"),c="feature:".concat(r),u=s(),i||(u?t.increment(a,["action:enabled",c]):t.increment(a,["action:disabled",c]),i=!0),u;var s,a,c,u}}}var bg="queue:multi",vg={channelObservable:null,topicNotifications:{}},mg=function(e){var t=e.queueId,n=e.name,r=e.state,i=e.medias;return new Yy({id:t,name:n,status:Qy(r),medias:i})},yg=function(e){var t=e.pubsub,n=e.cache;n||(n=vg);var r=n.channelObservable,i=n.topicNotifications||{};return function(e){var o=k.map(k.concat("queue:"),e);return Gv.Observable.create((function(s){if(r){!function(e){var t=e.queueIds,n=e.observer;t.forEach((function(e){var t=i[e];if(t)return n.next(t)}))}({queueIds:e,observer:s}),r.flatMap((function(e){return e.watchNewTopics(o)})).toPromise().catch((function(e){return nm.warn("Unable to update queue pubsub channel topics ",e)}))}else(r=t.joinChannel(bg,{topics:o}).do((function(){return nm.info("Joined ".concat(bg," topic"))})).publishReplay(1)).connect(),n.channelObservable=r;return r.flatMap((function(e){return e.observable("change")})).map(zy({queue_id:"queueId"})).filter((function(t){var n=t.queueId;return-1!==e.indexOf(n)})).map(mg).do((function(e){i[e.id]=e})).subscribe(s)}))}},gg=function(e){var t=e.queueIds;return(0,e.observeQueueStateUpdates)(t).scan((function(e,t){var n=k.findIndex(k.propEq("id",t.id))(e);return-1===n?k.append(t,e):k.equals(k.find(k.propEq("id",t.id))(e),t)?e:k.update(n,t,e)}),[]).distinctUntilChanged((function(e,t){return e===t}))};var _g=function(e){var t=e.queueIds;return(0,e.observeQueueStateUpdates)(t).groupBy(k.prop("id")).flatMap((function(e){return e.distinctUntilChanged()}))},wg=function(e,t){if(!e)throw new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Queue IDs list is undefined"});if(k.isEmpty(e))throw new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Queue IDs list is empty"});if(!t)throw new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Listener is undefined"})},Eg=function(e){var t=e.enabled,n=e.createQueueStateObservable,r=e.createQueueStateAccumulateObservable,i=e.pubsub;r||(r=gg),n||(n=_g);var o=function(e){var n=e.queueIds,o=e.listener;if(t){var s=new Gv.Subscription;wg(n,o);try{var a=r({queueIds:n,observeQueueStateUpdates:yg({pubsub:i})});s.add(a.subscribe(o,nm.error.bind(nm,"Failed to receive queue state list updates")))}catch(e){nm.error("Failed subscribe to queue state list updates",e)}return s}};return{subscribe:function(e,r){if(t){var o=new Gv.Subscription;wg(e,r);try{var s=n({queueIds:e,observeQueueStateUpdates:yg({pubsub:i})}).publish();o.add(s.subscribe(r,nm.error.bind(nm,"Failed to receive queue state updates"))),o.add(function(e,t){var n=new Gv.Subscription;return n.add(t.bufferCount(e.length).take(1).subscribe((function(e){return nm.info("Received initial queue states",{queue_states:k.map((function(e){return{id:e.id,status:e.state.status}}),e)})}))),n.add(t.skip(e.length).subscribe((function(e){return nm.info("Received queue state update",{queue_id:e.id,queue_status:e.state.status})}))),n}(e,s)),o.add(s.connect())}catch(e){nm.error("Failed subscribe to queue state updates",e)}}},subscribeToList:o,subscribeToListAsObservable:function(e){var t=e.queueIds,n=e.subscribeToListFn;return n||(n=o),t?Gv.Observable.create((function(e){return n({queueIds:t,listener:e.next.bind(e)})})):Gv.Observable.empty()}}},Og=function(){function e(){s(this,e)}return c(e,[{key:"start",value:function(e,t){var n=t.routingObservable;return this.ruleTracker(t,e).pipe(vb((function(r){var i,o=t.queuesAvailabilityObservable.debounceTime(100,i);return dt(t.currentStatusObservable,o).pipe($b(1),ub((function(t){var i=g(t,2),o=i[0],s=i[1];return{overseerApi:e,bufferedEvents:r,currentStatus:o,queuesState:s,routingObservable:n}})))}))).subscribe(this.actUponRules,(function(e){return nm.error("Error from business rule subscription: ".concat(k.prop("message",e)||e),e)}))}},{key:"ruleTracker",value:function(t,n,r){var i=t.rules,o=t.domInsertObservable,s=t.buildRuleObservable,a=t.overseerXhrEnabled?Mn(e.BUFFER_TIME,r):Mn(e.BUFFER_TIME,r).pipe(zb(n.connectedObservable.pipe(eb(k.equals(!0)),$b(1))));return Ft(i).pipe(vb(Tg),vb(function(e){var t=e.domInsertObservable,n=e.buildRuleObservable;return function(e){return qy.observable(e,t).pipe(Kb((function(t){return n(e,t)})),ub((function(t){return k.merge({attrs:t},e)})))}}({domInsertObservable:o,buildRuleObservable:s})),lv(a),bb((function(e){return e.toArray()})),vv(a,(function(e,t){return e})),eb((function(e){return e.length>0})))}},{key:"actUponRules",value:function(e){var t=e.overseerApi,n=e.currentStatus,r=e.queuesState,i=e.bufferedEvents,o=e.controller,s=void 0===o?Dm:o,a=["visitor_status"];r&&a.push("queues_availability"),i=k.map((function(e){var t=k.map(k.prop("type"),e.conditions);return!k.isEmpty(k.difference(t,a))?k.merge(e,{actions:[],send_to_server:!0}):e}),i);var c=k.filter((function(e){return function(e){var t=e.event,n=e.currentStatus,r=e.queuesState,i=k.all((function(e){return function(e,t,n){return"visitor_status"===e.type?-1!==e.status.indexOf(t):"queues_availability"!==e.type||function(e,t){var n=g(k.partition(k.pathEq(["state","status"],"open"))(t),2),r=n[0],i=n[1],o=function(t){var n=t.id;return k.contains(n,e.queueIds)};if("can_enqueue"===e.compareType)return k.any(o,r);if("cannot_enqueue"===e.compareType)return k.any(o,i)}(zy({queue_ids:"queueIds",compare_type:"compareType"},e),n)}(e,n,r)}),t.conditions);i&&nm.log("Business rule source matched: ",k.mergeAll([{rule_name:k.prop("name",t)},k.pick(["send_to_server"],t),k.pick(["type","source_attributes"],t.attrs),{url:window.location.href,source_id:t.attrs.id,rule_id:t.id}]));return i}({event:e,currentStatus:n,queuesState:r})}),i),u=k.groupBy((function(e){return e.send_to_server?"serverEvents":"browserEvents"}))(c),l=u.serverEvents||[],p=u.browserEvents||[];c.forEach((function(e){var t=e.actions,n=e.attrs,r=e.id,i=e.name,o=e.browser_event_conditions;if(!k.isEmpty(t))return function(e,t,n,r,i,o){e.forEach((function(e){var s={rule_id:n,rule_name:r,browser_event_conditions:o},a=k.merge(s,function(e,t){t||(t={});if(e.fields){var n=function(e,t){var n={};return t.forEach((function(t){var r=t.key,i=t.value,o=t.custom_value,s="custom"===i?o:e[i];n[r]=s})),n}(k.merge({visitor_id:Jv(),site_id:Xv(),url:window.location.href},t),e.fields);return k.merge(e,{fields:n})}return e}(e,t));i.triggerAction(a)}))}(t,n.source_attributes,r,i,s,o)})),k.isEmpty(l)||kg(t,a,k.map((function(e){var t=e.attrs,n=e.id;return k.assoc("rule_id",n,t)}))(l));var f=k.filter((function(e){var t=e.actions;return!k.isEmpty(t)}),p),h=k.map((function(e){var t=e.actions;return{ruleId:e.id,actionTypes:k.pluck("type",t)}}),f);k.isEmpty(h)||function(e){var t=e.overseerApi,n=e.browserEvents;xg?t.sendOverseerMetrics({browserEvents:n}):t.actionsShortcircuited({browserEvents:n})}({overseerApi:t,browserEvents:h})}}],[{key:"init",value:function(t,n){var r=n.currentStatusObservable,i=n.internalVisitorStateObservable,o=n.rules,s=n.queuesAvailabilityObservable,a=n.routingObservable,c=n.overseerXhrEnabled,u=Ee.create((function(e){var t=new MutationObserver((function(t){return k.forEach((function(t){return k.forEach((function(t){if(t instanceof HTMLElement)return e.next(t)}),t.addedNodes)}),t)}));return t.observe(document.body,{attributes:!1,characterData:!1,childList:!0,subtree:!0,attributeOldValue:!1,characterDataOldValue:!1}),function(){return t.disconnect()}})),l=Ly.buildObservable(i);return(new e).start(t,{currentStatusObservable:r,queuesAvailabilityObservable:s,rules:o,domInsertObservable:u,buildRuleObservable:l,routingObservable:a,overseerXhrEnabled:c})}}]),e}();function Sg(e){return e.operator?Sg(e.left).concat(Sg(e.right)):[e]}function Tg(e){var t;t=Array.isArray(e.sources)?e.sources:Sg(e.sources);var n=k.map((function(t){return k.assoc("sources",t,e)}),t);return Ft(n)}function kg(e,t,n){e.sourcesTriggered({events:n,resolvedConditions:t,tabId:sm.tabId,initTimestamp:Og.INIT_TIMESTAMP})}Og.BUFFER_TIME=100,Og.INIT_TIMESTAMP=(new Date).getTime();var xg=sm.conf.visitor_api.disable_overseer_actions_shortcircuited;var Ag=function(e){return{response:(t=e,t instanceof XMLHttpRequest?e.response:e)};var t},Ig=function(e){var t=e.stats,n=e.protocol,r=e.failureTagProperty,i=e.timeout,o=e.timeoutError,s=e.logResponse,a=e.scheduler;return function(e,c){var u=e.resource,l=e.method,p=t.statApiUsage({protocol:n,resource:u})(l).attempted();return c().do(p.succeeded,k.compose(p.failed,k.prop(r))).timeoutWith(i,o.do(null,p.timedOut),a).do((function(e){var t={};!1!==s&&(t=Ag(e)),nm.log("Successfully executed '".concat(l,"' on resource ").concat(u),t)}),(function(e){return nm.warn("Failed to execute '".concat(l,"' on resource ").concat(u),Ag(e))})).finally((function(){if(!p.isFinished())return p.failed("aborted")}))}},Ng=new Error({cause:"Internal error"});function Cg(e,t){var n=e.wsProxy,r=e.stats,i=Ig({stats:r,protocol:"rest",failureTagProperty:"message",timeout:5e3,timeoutError:ur(Ng),scheduler:t}),o=function(e){return r.increment("sm.service.overseer_api.action_shortcircuited",["type:".concat(e),"site_id:".concat(Xv())])},s=function(){return{visitor_id:Jv(),site_id:Xv(),url:window.location.href}};return{sourcesTriggered:function(e){var t=e.events,r=e.tabId,o=e.resolvedConditions;return i({resource:"overseer",method:"sources_triggered"},(function(){return n.request({method:"POST",url:"".concat(sm.conf.api_url,"/overseer/sources_triggered"),payload:k.merge(s(),{events:t,tab_id:r,resolved_conditions:o}),headers:{"content-type":"application/json"}})})).subscribe((function(){}),(function(){}))},actionsShortcircuited:function(e){var t=e.browserEvents,r={browser_events:k.map((function(e){return{rule_id:e.ruleId,action_types:e.actionTypes}}),t)};return i({resource:"overseer",method:"actions_shortcircuited"},(function(){return n.request({method:"POST",url:"".concat(sm.conf.api_url,"/overseer/actions_shortcircuited"),payload:k.merge(s(),r),headers:{"content-type":"application/json"}})})).subscribe((function(){}),(function(){}))},sendOverseerMetrics:function(e){var t=e.browserEvents;k.forEach(o,t.map((function(e){return e.actionTypes})))},connectedObservable:n.connectedObservable}}var Rg=[sm.conf.api_url,"libs.salemove.com","libs.glia.com","visitor.local.dev"],Pg=function(e){return k.any((function(t){return k.contains(t,e)}),Rg)},Mg=function(e){if("string"!=typeof e&&(t=e,n=new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$","i"),!Boolean(n.test(t))))return nm.warn("Invalid URL provided",{rawUrl:e}),!1;var t,n;try{var r=new window.URL(e);return Pg(r.origin)}catch(t){try{var i=e.trim();return Boolean(i)&&i.length>2&&Pg(i)}catch(t){return nm.warn("Error validating URL",{rawUrl:e,error:t}),!1}}},jg=k.pick(["response","status","statusText","readyState","responseURL"]),Lg=function(e){var t=e.method,n=e.url,r=e.payload,i=e.responseType,o=e.getRequestHeaders,s=e.onUploadProgress,a=e.onSuccess,c=e.onError,u=new XMLHttpRequest;if(u.open(t,n,!0),o){var l=o();Object.keys(l).forEach((function(e){var t=l[e];u.setRequestHeader(e,t)}))}return u.responseType=i,u.onreadystatechange=function(){if(4===u.readyState)if(u.status>=200&&u.status<300)if("json"===i&&"string"==typeof u.response)try{var e=k.assoc("response",u.response.length>0?JSON.parse(u.response):"",u);a(e)}catch(e){nm.error("Could not parse response json in IE11",{error:e,server_response:u.response}),c(u)}else a(u);else c(u)},s&&u.upload.addEventListener("progress",(function(e){e.lengthComputable&&s({loaded:e.loaded,total:e.total})}),!1),Mg(n)?u.send("GET"===t?void 0:r):(nm.error("Trying to fetch from invalid URL",{rawUrl:n}),c(u)),function(){return u.abort()}},qg=function(e){var t=e.method,n=e.url,r=e.payload,i=e.responseType,o=e.getRequestHeaders,s=e.onUploadProgress,a=e.sendRequest,c=e.contentType;if(!Mg(n))return nm.error("Trying to fetch from invalid URL",{rawUrl:n}),ur(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR,message:"Request URL is invalid"}));var u="application/json"===c&&"string"!=typeof r?JSON.stringify(r):r;return t=t||"GET",i=i||"json",a=a||Lg,o||(o=function(){return{Accept:"application/vnd.salemove.private+json",Authorization:"Bearer "+sm.accessToken}}),Ee.create((function(e){return a({method:t,url:n,payload:u,responseType:i,getRequestHeaders:c?function(){return k.merge(o(),{"Content-Type":c})}:o,onUploadProgress:s,onSuccess:function(t){e.next(t),e.complete()},onError:function(t){return e.error(jg(t))}})}))},Ug=function(e){var t=e.url,n=e.method,r=e.payload,i=e.responseType,o=e.contentType,s=e.getRequestHeaders,a=e.calculateAttemptDelay,c=e.retryLimit,u=void 0===c?5:c,l=e.onSuccess,p=e.onError,f=void 0===p?function(){}:p,h=e.onAttempt,d=void 0===h?function(){}:h,b=e.onAttemptError,v=void 0===b?function(){}:b,m=e.shouldRetry,y=void 0===m?function(){return!0}:m;N({calculateAttemptDelay:a,attempt:function(e){var a=e.repeat;d(),Lg({method:n,url:t,payload:r,responseType:i,getRequestHeaders:o?function(){return k.merge(s(),{"Content-Type":o})}:s,onError:function(e){var t=y(e.status);v(t),(t?a:f)(e)},onSuccess:l})},onGiveUp:f,retryLimit:u})},Dg=function(e,t){var n=e.url,r=e.assetKey,i=e.onError,o=e.onSuccess,s=e.identifier,a={method:"GET",responseType:"json",onSuccess:function(e){t.increment("sm.assets.load",["action:succeeded","asset:".concat(r)]),o(e)},onAttempt:function(){t.increment("sm.assets.load",["action:attempted","asset:".concat(r)])},onAttemptError:function(e){nm.warn("Failed fetching ".concat(r).concat(e?", retrying":""),{asset_url:n,identifier:s}),t.increment("sm.assets.load",["action:warning","asset:".concat(r)])},onError:function(){nm.warn("Error fetching ".concat(r),{asset_url:n,identifier:s}),t.increment("sm.assets.load",["action:failed","asset:".concat(r)]),"function"==typeof i&&i()}};Ug(k.merge(a,e))},Vg=new Error({cause:"Internal error"});function Fg(e,t){var n=e.stats,r=Ig({stats:n,protocol:"rest",failureTagProperty:"message",timeout:5e3,timeoutError:ur(Vg),scheduler:t}),i=function(e){return n.increment("sm.service.overseer_api.action_shortcircuited",["type:".concat(e),"site_id:".concat(Xv())])},o=function(){return{visitor_id:Jv(),site_id:Xv(),url:window.location.href}},s=0;return{sourcesTriggered:function(e){var t=e.events,n=e.tabId,i=e.resolvedConditions,a=e.initTimestamp,c=e.xhrAsObservable,u=void 0===c?qg:c;s++;var l=k.merge(o(),{events:t,tab_id:n,init_timestamp:a,request_number:s,resolved_conditions:i});return r({resource:"overseer",method:"sources_triggered"},(function(){return u({method:"POST",url:"".concat(sm.conf.api_url,"/overseer/sources_triggered"),payload:l,contentType:"application/json"})})).subscribe((function(){}),(function(){}))},actionsShortcircuited:function(e){var t=e.browserEvents,n=e.xhrAsObservable,i=void 0===n?qg:n,s={browser_events:k.map((function(e){return{rule_id:e.ruleId,action_types:e.actionTypes}}),t)};return r({resource:"overseer",method:"actions_shortcircuited"},(function(){return i({method:"POST",url:"".concat(sm.conf.api_url,"/overseer/actions_shortcircuited"),payload:k.merge(o(),s),contentType:"application/json"})})).subscribe((function(){}),(function(){}))},sendOverseerMetrics:function(e){var t=e.browserEvents;k.forEach(i,t.map((function(e){return e.actionTypes})))}}}var Bg=function(e){var t=function(e){return k.compose(k.reject(k.isNil),k.chain(k.prop("queue_ids")),k.chain(k.prop("conditions")))(e)}(e)||[],n=function(e){return k.compose(k.reject(k.isNil),k.chain(k.path(["browser_event_conditions","queue_ids"])))(e)}(e)||[],r=t.concat(n);return k.uniq(r)},Hg=function(e){return k.filter(k.compose(k.or(k.isEmpty,k.isNil),k.chain(k.propOr([],"queue_ids")),k.prop("conditions")))(e)},Wg=function(e){return k.filter(k.compose(k.isEmpty,k.pathOr([],["browser_event_conditions","queue_ids"])))(e)};function Gg(e){var t=e.cobraObservable,n=e.internalVisitorStateObservable,r=e.volatileNotifications,i=e.stats,o=e.wsProxy,s=e.currentStatusObservable,a=e.queuesStateUpdatesObservable,c=e.routingObservable;new Dm({volatileNotifications:r,cobraObservable:t,routingObservable:c}).start();var u=new dg(sm.conf,i,"visitor_api","overseer_xhr_enabled_percentage"),l=sm.conf.visitor_api.enable_xhr_to_overseer&&u.enabledForVisitor(Jv()),p=l?new Fg({stats:i}):new Cg({wsProxy:o,stats:i}),f=sm.conf.overseer.rules,h=sm.conf.omniq.omniq_enabled?f:function(e){return k.compose(Hg,Wg)(e)}(f),d=Bg(h),b=function(){if(k.not(k.isEmpty(d))){var e=new Gv.ReplaySubject(1);return a.subscribeToList({queueIds:d,listener:e.next.bind(e)}),e}return Gv.Observable.of(null)}();Og.init(p,{currentStatusObservable:s.startWith("available"),internalVisitorStateObservable:n,queuesAvailabilityObservable:b,rules:h,routingObservable:c,overseerXhrEnabled:l})}function zg(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=!1!==r.rethrow;return function(){try{return n.apply(this,arguments)}catch(n){if(rm.clientHandlerError(t),nm.warn(e,n),i)throw n;console.error(n)}}}var Jg=k.curryN(2,(function(e,t){return k.compose(k.forEach((function(t){var n=g(t,2),r=n[0],i=n[1];return e(r,i)})),k.toPairs)(t)})),Qg=function(){var e={},t=function(e,t){return zg("Event handler for ".concat(e," threw an error"),e,t,{rethrow:!1})},n=function(n,r){var i=(e[n]||{}).listenerEntries||[],o=k.compose(k.map((function(e){var i=e.listener;return{listener:i,subscription:r.subscribe(t(n,i),nm.error)}})),k.forEach((function(e){return e.subscription.unsubscribe()})))(i);e[n]={observable:r,listenerEntries:o}};return{observable:function(t){return e[t].observable},addEventListener:function(n,r){var i=e[n]||{},o=i.listenerEntries||[],s=i.observable;if(!k.any(k.propEq("listener",r),o)){var a=s?s.subscribe(t(n,r),nm.error):Gv.Subscription.EMPTY,c=k.append({listener:r,subscription:a},o);return e[n]={listenerEntries:c,observable:s},null}},removeEventListener:function(t,n){var r=e[t]||{},i=r.listenerEntries||[],o=r.observable,s=k.find(k.propEq("listener",n))(i);if(s){s.subscription.unsubscribe();var a=k.without([s])(i);e[t]={observable:o,listenerEntries:a}}return null},proxy:n,proxyAll:Jg(n),eventWithoutListenerObservable:function(t){return(e[t]||{}).observable.filter((function(){return!function(t){var n=(e[t]||{}).listenerEntries||[];return k.not(k.isEmpty(n))}(t)}))},stop:function(){k.compose(k.forEach((function(e){return e.unsubscribe()})),k.map(k.prop("subscription")),k.chain(k.prop("listenerEntries")),k.values)(e),e={}}}},Yg=function(){var e=new Gv.Subscription,t=Qg(),n=function(n,r){var i=r.publishReplay(1);e.add(i.connect()),t.proxy(n,i)};return{addEventListener:t.addEventListener,removeEventListener:t.removeEventListener,eventWithoutListenerObservable:t.eventWithoutListenerObservable,proxy:n,proxyAll:Jg(n),stop:function(){e.unsubscribe(),t.stop()},observable:t.observable}};function Kg(e){var t=Yg();return t.proxy("change",e),{addEventListener:t.addEventListener,removeEventListener:t.removeEventListener}}var Xg=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:sm.tracker;return Kg(e.getUserIsActiveTabObservable())},$g=function(){return Kg(Gv.Observable.of(!0))};function Zg(e){var t=e.channelObservable,n=e.logger.withTags({feature:"cobra"}),r=t.flatMap((function(e){var t=e.channel,n=e.operator;return dm("Cobra").map((function(e){return{Cobra:e,channel:t,operator:n}}))})).distinctUntilChanged(null,(function(e){return e.channel.url})).switchMap((function(e){var t=e.Cobra,r=e.channel,i=e.operator,o=new t.SourceInitializer(r,Xg(),i.id,n),s=o.initialize(),a=function(){return o.stop()};return r.addDestroyListener((function(){return a()})),Gv.Observable.create((function(e){return e.next({cobraSourceInitializer:o,cobraSource:s,operator:i}),function(){return a()}}))})).do((function(e){var t=e.operator;return n.info("Cobra: Started successfully",{operator_id:t.id})}),n.error.bind(n,"Cobra: Failed to start"),(function(){return n.info("Cobra: Stopped and will not start again")})),i=r.publishReplay(1);return sm.cobraSubscription=i.connect(),{cobraObservable:r=i.filter(k.pathEq(["cobraSource","status"],"started"))}}var e_={UNKNOWN:"unknown",NESTED_COBROWSABLE_IFRAME:"nested_cobrowsable_visitor",ENGAGEMENT_IFRAME:"main_visitor"},t_="cobrowsable_iframe_id",n_="sm:source:nested_cobrowsable_iframe:channel_url",r_="sm:iframe_context_check",i_=function e(t,n){var r=function(e,t){for(var n=e.querySelectorAll("iframe"),r=0;r0&&void 0!==arguments[0]?arguments[0]:this.timeout;if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}},{key:"onClose",value:function(e){this.on(T_,e)}},{key:"onError",value:function(e){return this.on(k_,(function(t){return e(t)}))}},{key:"on",value:function(e,t){var n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}},{key:"off",value:function(e,t){this.bindings=this.bindings.filter((function(n){return!(n.event===e&&(void 0===t||t===n.ref))}))}},{key:"canPush",value:function(){return this.socket.isConnected()&&this.isJoined()}},{key:"push",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.timeout;if(t=t||{},!this.joinedOnce)throw new Error("tried to push '".concat(e,"' to '").concat(this.topic,"' before joining. Use channel.join() before pushing events"));var r=new P_(this,e,(function(){return t}),n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}},{key:"leave",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=S_;var n=function(){e.socket.hasLogger()&&e.socket.log("channel","leave ".concat(e.topic)),e.trigger(T_,"leave")},r=new P_(this,I_,p_({}),t);return r.receive("ok",(function(){return n()})).receive("timeout",(function(){return n()})),r.send(),this.canPush()||r.trigger("ok",{}),r}},{key:"onMessage",value:function(e,t,n){return t}},{key:"isMember",value:function(e,t,n,r){return this.topic===e&&(!r||r===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:n,joinRef:r}),!1))}},{key:"joinRef",value:function(){return this.joinPush.ref}},{key:"rejoin",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=O_,this.joinPush.resend(e))}},{key:"trigger",value:function(e,t,n,r){var i=this.onMessage(e,t,n,r);if(t&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");for(var o=this.bindings.filter((function(t){return t.event===e})),s=0;s1&&void 0!==arguments[1]?arguments[1]:{};s(this,e);var i=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onChange:null,onJoin:null,onLeave:null,onSync:function(){}},this.channel.on(i.state,(function(t){var r=n.caller,i=r.onChange,o=r.onJoin,s=r.onLeave,a=r.onSync;n.joinRef=n.channel.joinRef(),o||s?e.syncState(n.state,t,o,s):e.synchronizeState(n.state,t,i),n.pendingDiffs.forEach((function(t){o||s?e.syncDiff(n.state,t,o,s):e.synchronizeDiff(n.state,t,i)})),n.pendingDiffs=[],a()})),this.channel.on(i.diff,(function(t){var r=n.caller,i=r.onChange,o=r.onJoin,s=r.onLeave,a=r.onSync;n.inPendingSyncState()?n.pendingDiffs.push(t):(o||s?e.syncDiff(n.state,t,o,s):e.synchronizeDiff(n.state,t,i),a())}))}return c(e,[{key:"onJoin",value:function(e){console&&console.warn&&console.warn("onJoin is deprecated, use onChange instead"),this.caller.onJoin=e}},{key:"onLeave",value:function(e){console&&console.warn&&console.warn("onLeave is deprecated, use onChange instead"),this.caller.onLeave=e}},{key:"onChange",value:function(e){this.caller.onChange=e}},{key:"onSync",value:function(e){this.caller.onSync=e}},{key:"list",value:function(t){return e.list(this.state,t)}},{key:"inPendingSyncState",value:function(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}}],[{key:"synchronizeState",value:function(e,t,n){var r={},i={};return this.map(e,(function(e,n){t[e]||(i[e]=n)})),this.map(t,(function(t,n){var o=e[t];if(o){var s=n.metas.map((function(e){return e.phx_ref})),a=o.metas.map((function(e){return e.phx_ref})),c=n.metas.filter((function(e){return a.indexOf(e.phx_ref)<0})),u=o.metas.filter((function(e){return s.indexOf(e.phx_ref)<0}));c.length>0&&(r[t]=n,r[t].metas=c),u.length>0&&(c.length>0?i[t]={metas:u}:(i[t]=n,i[t].metas=u))}else r[t]=n})),this.synchronizeDiff(e,{joins:r,leaves:i},n)}},{key:"syncState",value:function(e,t,n,r){var i=this,o=this.clone(e),s={},a={};return this.map(o,(function(e,n){t[e]||(a[e]=n)})),this.map(t,(function(e,t){var n=o[e];if(n){var r=t.metas.map((function(e){return e.phx_ref})),c=n.metas.map((function(e){return e.phx_ref})),u=t.metas.filter((function(e){return c.indexOf(e.phx_ref)<0})),l=n.metas.filter((function(e){return r.indexOf(e.phx_ref)<0}));u.length>0&&(s[e]=t,s[e].metas=u),l.length>0&&(a[e]=i.clone(n),a[e].metas=l)}else s[e]=t})),this.syncDiff(o,{joins:s,leaves:a},n,r)}},{key:"synchronizeDiff",value:function(e,t,n){var r=t.joins,i=t.leaves,o={};return this.map(r,(function(e,t){o[e]={joinedMetas:t.metas,leftMetas:[],update:t}})),this.map(i,(function(e,t){o[e]?o[e].leftMetas=t.metas:o[e]={joinedMetas:[],leftMetas:t.metas,update:t}})),this.map(o,(function(t,r){var i=r.joinedMetas,o=r.leftMetas,s=r.update,a=i.map((function(e){return e.phx_ref})),c=o.map((function(e){return e.phx_ref})),u=e[t],l={metas:u?u.metas:[]};l.metas=l.metas.filter((function(e){return-1===a.indexOf(e.phx_ref)})).concat(i).filter((function(e){return-1===c.indexOf(e.phx_ref)})),Object.keys(s).forEach((function(e){"metas"!==e&&(l[e]=s[e])})),0===l.metas.length?delete e[t]:e[t]=l,n&&n(t,u,l)})),e}},{key:"syncDiff",value:function(e,t,n,r){var i=this,o=this.clone(t),s=o.joins,a=o.leaves;return n||(n=function(){}),r||(r=function(){}),this.map(s,(function(t,r){var o=e[t];if(e[t]=i.clone(r),o){var s,a=e[t].metas.map((function(e){return e.phx_ref})),c=o.metas.filter((function(e){return a.indexOf(e.phx_ref)<0}));(s=e[t].metas).unshift.apply(s,_(c))}n(t,o,r)})),this.map(a,(function(t,n){var i=e[t];if(i){var o=n.metas.map((function(e){return e.phx_ref}));i.metas=i.metas.filter((function(e){return o.indexOf(e.phx_ref)<0})),r(t,i,n),0===i.metas.length&&delete e[t]}})),e}},{key:"list",value:function(e,t){return t||(t=function(e,t){return t}),this.map(e,(function(e,n){return t(e,n)}))}},{key:"map",value:function(e,t){return Object.getOwnPropertyNames(e).map((function(n){return t(n,e[n])}))}},{key:"clone",value:function(e){return JSON.parse(JSON.stringify(e))}}]),e}(),D_={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode:function(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));var n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))},decode:function(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));var n=g(JSON.parse(e),5);return t({join_ref:n[0],ref:n[1],topic:n[2],event:n[3],payload:n[4]})},binaryEncode:function(e){var t=e.join_ref,n=e.ref,r=e.event,i=e.topic,o=e.payload,s=this.META_LENGTH+t.length+n.length+i.length+r.length,a=new ArrayBuffer(this.HEADER_LENGTH+s),c=new DataView(a),u=0;c.setUint8(u++,this.KINDS.push),c.setUint8(u++,t.length),c.setUint8(u++,n.length),c.setUint8(u++,i.length),c.setUint8(u++,r.length),Array.from(t,(function(e){return c.setUint8(u++,e.charCodeAt(0))})),Array.from(n,(function(e){return c.setUint8(u++,e.charCodeAt(0))})),Array.from(i,(function(e){return c.setUint8(u++,e.charCodeAt(0))})),Array.from(r,(function(e){return c.setUint8(u++,e.charCodeAt(0))}));var l=new Uint8Array(a.byteLength+o.byteLength);return l.set(new Uint8Array(a),0),l.set(new Uint8Array(o),a.byteLength),l.buffer},binaryDecode:function(e){var t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush:function(e,t,n){var r=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),s=this.HEADER_LENGTH+this.META_LENGTH-1,a=n.decode(e.slice(s,s+r));s+=r;var c=n.decode(e.slice(s,s+i));s+=i;var u=n.decode(e.slice(s,s+o));return s+=o,{join_ref:a,ref:null,topic:c,event:u,payload:e.slice(s,e.byteLength)}},decodeReply:function(e,t,n){var r=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),s=t.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(a,a+r));a+=r;var u=n.decode(e.slice(a,a+i));a+=i;var l=n.decode(e.slice(a,a+o));a+=o;var p=n.decode(e.slice(a,a+s));a+=s;var f=e.slice(a,e.byteLength);return{join_ref:c,ref:u,topic:l,event:A_,payload:{status:p,response:f}}},decodeBroadcast:function(e,t,n){var r=t.getUint8(1),i=t.getUint8(2),o=this.HEADER_LENGTH+2,s=n.decode(e.slice(o,o+r));o+=r;var a=n.decode(e.slice(o,o+i));return o+=i,{join_ref:null,ref:null,topic:s,event:a,payload:e.slice(o,e.byteLength)}}},V_=function(){function e(t){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};s(this,e),this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=r.timeout||1e4,this.transport=r.transport||d_.WebSocket||q_,this.establishedConnections=0,this.defaultEncoder=D_.encode.bind(D_),this.defaultDecoder=D_.decode.bind(D_),this.closeWasClean=!1,this.binaryType=r.binaryType||"arraybuffer",this.connectClock=1,this.transport!==q_?(this.encode=r.encode||this.defaultEncoder,this.decode=r.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);var i=null;h_&&h_.addEventListener&&(h_.addEventListener("pagehide",(function(e){n.conn&&(n.disconnect(),i=n.connectClock)})),h_.addEventListener("pageshow",(function(e){i===n.connectClock&&(i=null,n.connect())}))),this.heartbeatIntervalMs=r.heartbeatIntervalMs||3e4,this.rejoinAfterMs=function(e){return r.rejoinAfterMs?r.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4},this.reconnectAfterMs=function(e){return r.reconnectAfterMs?r.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3},this.logger=r.logger||null,this.longpollerTimeout=r.longpollerTimeout||2e4,this.params=p_(r.params||{}),this.endPoint="".concat(t,"/").concat(C_),this.vsn=r.vsn||b_,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new M_((function(){n.teardown((function(){return n.connect()}))}),this.reconnectAfterMs)}return c(e,[{key:"replaceTransport",value:function(e){this.disconnect(),this.transport=e}},{key:"protocol",value:function(){return location.protocol.match(/^https/)?"wss":"ws"}},{key:"endPointURL",value:function(){var e=L_.appendParams(L_.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?"".concat(this.protocol(),":").concat(e):"".concat(this.protocol(),"://").concat(location.host).concat(e)}},{key:"disconnect",value:function(e,t,n){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(e,t,n)}},{key:"connect",value:function(e){var t=this;this.connectClock++,e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=p_(e)),this.conn||(this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=function(){return t.onConnOpen()},this.conn.onerror=function(e){return t.onConnError(e)},this.conn.onmessage=function(e){return t.onConnMessage(e)},this.conn.onclose=function(e){return t.onConnClose(e)})}},{key:"log",value:function(e,t,n){this.logger(e,t,n)}},{key:"hasLogger",value:function(){return null!==this.logger}},{key:"onOpen",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}},{key:"onClose",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}},{key:"onError",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}},{key:"onMessage",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}},{key:"onConnOpen",value:function(){this.hasLogger()&&this.log("transport","connected to ".concat(this.endPointURL())),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach((function(e){return(0,g(e,2)[1])()}))}},{key:"heartbeatTimeout",value:function(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.abnormalClose("heartbeat timeout"))}},{key:"resetHeartbeat",value:function(){var e=this;this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,clearTimeout(this.heartbeatTimer),setTimeout((function(){return e.sendHeartbeat()}),this.heartbeatIntervalMs))}},{key:"teardown",value:function(e,t,n){var r=this;if(!this.conn)return e&&e();this.waitForBufferDone((function(){r.conn&&(t?r.conn.close(t,n||""):r.conn.close()),r.waitForSocketClosed((function(){r.conn&&(r.conn.onclose=function(){},r.conn=null),e&&e()}))}))}},{key:"waitForBufferDone",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;5!==n&&this.conn&&this.conn.bufferedAmount?setTimeout((function(){t.waitForBufferDone(e,n+1)}),150*n):e()}},{key:"waitForSocketClosed",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;5!==n&&this.conn&&this.conn.readyState!==g_?setTimeout((function(){t.waitForSocketClosed(e,n+1)}),150*n):e()}},{key:"onConnClose",value:function(e){var t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),clearTimeout(this.heartbeatTimer),this.closeWasClean||1e3===t||this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((function(t){return(0,g(t,2)[1])(e)}))}},{key:"onConnError",value:function(e){this.hasLogger()&&this.log("transport",e);var t=this.transport,n=this.establishedConnections;this.stateChangeCallbacks.error.forEach((function(r){(0,g(r,2)[1])(e,t,n)})),(t===this.transport||n>0)&&this.triggerChanError()}},{key:"triggerChanError",value:function(){this.channels.forEach((function(e){e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(k_)}))}},{key:"connectionState",value:function(){switch(this.conn&&this.conn.readyState){case v_:return"connecting";case m_:return"open";case y_:return"closing";default:return"closed"}}},{key:"isConnected",value:function(){return"open"===this.connectionState()}},{key:"remove",value:function(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((function(t){return t.joinRef()!==e.joinRef()}))}},{key:"off",value:function(e){for(var t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter((function(t){var n=g(t,1)[0];return-1===e.indexOf(n)}))}},{key:"channel",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new j_(e,t,this);return this.channels.push(n),n}},{key:"push",value:function(e){var t=this;if(this.hasLogger()){var n=e.topic,r=e.event,i=e.payload,o=e.ref,s=e.join_ref;this.log("push","".concat(n," ").concat(r," (").concat(s,", ").concat(o,")"),i)}this.isConnected()?this.encode(e,(function(e){return t.conn.send(e)})):this.sendBuffer.push((function(){return t.encode(e,(function(e){return t.conn.send(e)}))}))}},{key:"makeRef",value:function(){var e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}},{key:"sendHeartbeat",value:function(){var e=this;this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimer=setTimeout((function(){return e.heartbeatTimeout()}),this.heartbeatIntervalMs))}},{key:"abnormalClose",value:function(e){this.closeWasClean=!1,this.isConnected()&&this.conn.close(1e3,e)}},{key:"flushSendBuffer",value:function(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((function(e){return e()})),this.sendBuffer=[])}},{key:"onConnMessage",value:function(e){var t=this;this.decode(e.data,(function(e){var n=e.topic,r=e.event,i=e.payload,o=e.ref,s=e.join_ref;o&&o===t.pendingHeartbeatRef&&(clearTimeout(t.heartbeatTimer),t.pendingHeartbeatRef=null,setTimeout((function(){return t.sendHeartbeat()}),t.heartbeatIntervalMs)),t.hasLogger()&&t.log("receive","".concat(i.status||""," ").concat(n," ").concat(r," ").concat(o&&"("+o+")"||""),i);for(var a=0;a0&&!t.onlyLongPollEnabled){var n=setInterval((function(){if("open"===e.connectionState()&&e.transport===q_){var n=H_(e,t);if(e.transport!==n)return e.transport=n,e.disconnect((function(){return e.connect()}))}}),t.avoidLongPollWorkerInterval);return function(){return clearInterval(n)}}}(e,n)}},selectNewTransport:function(){B_()&&!F_()&&(e.transport=H_(e,n))},stop:function(){t&&t()}}}var G_=function(e){return e===window.WebSocket?"WebSocket":e===q_?"LongPoll":"unknown"},z_=function(e){return"object"===o(e)?null==e?void 0:e.reason:e},J_={metrics:{}};function Q_(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{logPrefix:"PubSub"},o=r.logPrefix,s=0,a=!1;n=n||J_;var c=function(e){n.metrics.connectionMetric&&n.increment(n.metrics.connectionMetric,e)},u=function(t){return i(i({},{transport:G_(e.transport),online:B_(),visibility_state:document.visibilityState,error_count:s}),t)},l=function(t,n){var r=(n||{}).transport;return["transport:".concat(r||G_(e.transport)),"online:".concat(B_())].concat(t)},p=function(){a=!0,c(l(["action:connected"])),t.info("".concat(o," socket opened"),u({}))},f=function(e){if(e){var n=G_(window.WebSocket),r=u({reason:e.reason,type:e.type,code:e.code&&e.code.toString(),transport:n}),i=l(["action:disconnected","type:".concat(e.type),"code:".concat(e.code)],{transport:n});e.wasClean?(c(i.concat(["reason:closed"])),t.info("".concat(o," connection disconnected cleanly"),r)):F_()?(c(i.concat(["reason:closed"])),t.info("".concat(o," connection disconnected while tab was hidden"),r)):(c(i.concat(["reason:closed"])),t.info("".concat(o," connection disconnected"),r))}else{var s=G_(q_),a=u({reason:"unknown",type:"unknown",code:"unknown",transport:s}),p=l(["action:disconnected","type:unknown","reason:unknown","code:unknown"],{transport:s});c(p),t.info("".concat(o," connection disconnected"),a)}},h=function(e){var n=e&&e.type||"unknown";s+=1;var r=e&&e.target?u({type:n}):u({type:n,error:e});F_()?t.info("".concat(o," connection error while tab was hidden"),r):B_()?1!==s||a?(c(l(["action:error"])),t.warn("".concat(o," socket connection error"),r)):t.info("".concat(o," socket connection error while attempting to establish the connection first time"),r):t.info("".concat(o," connection error while user was offline"),r)},d=function(n){return t.info("".concat(o," failed to connect with initial transport"),{new_transport:G_(e.transport),error:z_(n)})},b=function(){return c(l(["action:connect"]))};return{onOpen:p,onClose:f,onError:h,onInitialTry:b,onInitialConnectError:d}}var Y_=function(e,t){var n=t.enabled,r=t.logPrefix;return n?function(t,n,i){return e.info("".concat(r," ").concat(t,": ").concat(n),{pubsub_data:i})}:function(){}},K_="sm.app.visitor_api.pubsub",X_="".concat(K_,".connection"),$_="".concat(K_,".push"),Z_=2147483647,ew=function(e){var t=e.server,n=e.socket,r=e.stats,i=e.logsEnabled,s=e.getAccessToken,a=e.visitorIdObservable,c=void 0===a?Yv():a,u=e.reconnectConf,l=void 0===u?{}:u,p=e.getVisitorPriority,f=e.renewAccessToken,h=null;l={initialDelay:l.initialDelay||3e3,maxDelay:l.maxDelay||6e4,delayFactor:l.delayFactor||1.5};var d=0,b=A(l.initialDelay,l.maxDelay,l.delayFactor);n||(n=new V_("".concat(t,"/notifications"),{logger:Y_(nm,{enabled:i,logPrefix:"[PubSub]"}),params:function(){return{access_token:s(),priority:p()}},reconnectAfterMs:function(e){return b(d)}}));var v=new W_(n),m=new Q_(n,nm,{increment:r.increment.bind(r),metrics:{connectionMetric:X_}},{logPrefix:"PubSub"}),y=new Gv.ReplaySubject(1),g=sm.conf.engagement.api_timeout_milliseconds||1e4;n.onOpen((function(){y.next(!0),m.onOpen()})),n.onClose((function(e){y.next(!1),d+=1,m.onClose(e),h&&n.disconnect()})),n.onError((function(e){if(y.next(!1),e&&e.status)switch(e.status){case 403:nm.info("Detected likely pubsub authentication error, reconnecting after max delay"),b.setNextDelayMinimum(l.maxDelay);break;case 503:var t=l.maxDelay/2;nm.info("PubSub unavailable, postponing reconnecting for at least ".concat(t," ms")),b.setNextDelayMinimum(t);break;default:return nm.error("Received unhandled pubsub error status ".concat(e.status,", stopping reconnecting")),void n.disconnect()}m.onError(e),v.selectNewTransport()}));var _=function(e){return"object"===o(e)?null==e?void 0:e.reason:e},w=function(e,t,i,o){var s=function(e){if("function"==typeof e)return e.modify=function(){throw new Error("Cannot modify channel params because it is a closure already")},e;var t=k.clone(e||{}),n=function(){return t};return n.modify=function(e,n){t[e]=n(t[e])},n}(t);o||(o={}),i||(i=[]);var a=Gv.Observable.create((function(a){var c=!1,u=(t||{}).timeout||Z_,l=n.channel(e,s);return l.join(u).receive("ok",(function(){c=!0,a.next(function(e,t){var n=function(t,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=i.disableStats,s=i.timeout;s||(s=g);var a=function(e,t){o||r.increment(e,t)};return Gv.Observable.create((function(r){return e.push(t,n,s).receive("ok",(function(e){r.next(e),r.complete()})).receive("error",(function(e){a($_,["action:error"]),r.error({type:"error",error:e})})).receive("timeout",(function(){a($_,["action:timeout"]),r.error({type:"timeout"})})),function(){}}))};return{observable:function(t,n){return n||(n={}),Gv.Observable.create((function(r){var i=e.on(t,(function(e){return r.next(e)}));return function(){e.off(t,i),n.leaveChannelOnDispose&&e.leave()}}))},push:n,phoenixChannel:e,leave:function(){return e.leave()},watchNewTopics:function(e){return t.modify("topics",(function(t){return k.union(t||[],e)})),n("watch",{topics:e},{timeout:Z_})}}}(l,s)),a.complete()})).receive("error",(function(t){t&&"join crashed"===t.reason?nm.info("Joining Pubsub channel failed with crash, retrying",{reason:"error",error:_(t),topic:e}):t&&"overload"===t.reason?nm.info("Joining Pubsub channel failed because of overload, retrying",{topic:e}):(t&&-1!==i.indexOf(t.reason)?nm.info("Joining Pubsub channel failed with expected reason",{reason:"error",error:_(t),topic:e}):nm.warn("Joining Pubsub channel failed",{reason:"error",error:_(t),topic:e}),a.error({type:"error",error:t}))})).receive("timeout",(function(){return nm.warn("Joining Pubsub channel failed",{reason:"timeout",topic:e})})),function(){c&&!o.leaveChannelOnDispose||l.leave()}}));return Gv.Observable.defer((function(){return v.ensureConnected({onInitialTry:function(){return m.onInitialTry},onInitialError:function(e){return m.onInitialConnectError(e)}}),Gv.Observable.of({})})).flatMapTo(y).filter(k.equals(!0)).take(1).flatMapTo(a)},E=c.switchMap((function(e){return w("visitor_volatile:".concat(e))})).publishReplay(1);E.connect(),E.flatMap((function(e){return e.observable("system:avoid_reconnection")})).subscribe((function(e){var t,r,i=e.duration_in_seconds;r=.5,i=(t=i)+Math.floor(Math.random()*r*t),nm.info("Disabling reconnections to pubsub",{duration_in_seconds:i}),h&&clearTimeout(h),h=setTimeout((function(){nm.info("Enabling reconnections to pubsub"),h=null,n.connect()}),1e3*i)}));var O,S,T,x=k.compose(k.not,k.isEmpty,k.symmetricDifference),I=function(e,t){return k.map((function(t){return"site_visitor:".concat(e,":").concat(t)}),t)},N=[];return{joinChannel:w,volatileChannelObservable:E,joinSiteVisitorNotifications:function(e,t){return!k.isEmpty(N)&&O&&S===e||(S=e,N=t,(O=w("site_visitor:".concat(e),{topics:I(e,N)}).publishReplay(1)).connect(),(T=O.flatMap((function(e){return(0,e.observable)("message")})).filter(k.identity).publishReplay(50)).connect()),x(t,N)&&(N=k.union(t,N),O.take(1).flatMap((function(t){return(0,t.watchNewTopics)(I(e,N))})).subscribe((function(){return nm.debug("Subscribed to additional sites",N)}),(function(e){return nm.warn("Error subscribing to additional sites",e,N)}))),T},connectedObservable:y.distinctUntilChanged(),disconnect:n.disconnect.bind(n),connect:n.connect.bind(n),reconnect:function(){return n.disconnect((function(){return n.connect()}))},renewTokenAndReconnectWaitForTeardown:function(e){var t=e.consolidationSecret;return f({consolidationSecret:t}).flatMap((function(){return Gv.Observable.create((function(e){n.disconnect((function(){n.connect(),e.next(),e.complete()}))}))}))},allowReconnection:function(){return null===h}}};function tw(e,t){var n=t.visitorId,r=t.visitorIdObservable,o=t.tabId,s=t.idleTimeoutSeconds,a=t.visitorMetadata;n=n||Jv(),r=r||Yv();var c="JOIN_NOT_REQUESTED",u="JOINING_ALLOW_REJECTION",l="JOINING_ALLOW_REJECTION_BUT_NO_REJECTION_REQUESTED",p="JOINING_NO_REJECTION",f="JOIN_REJECTED",h="JOINED",d="JOIN_ERROR",b="JOIN_REQUESTED_ALLOW_REJECTION",v="JOIN_REJECTED",m="JOIN_ERROR",y="JOIN_SUCCESSFUL",_="JOIN_REQUESTED_NO_REJECTION",w="VISITOR_ID_CHANGED",E="too_many_tracked",O=new Gv.ReplaySubject(1),S=function(t,n,r){var i="visitor_presence:".concat(t),c=n?[E]:[],u=!1;e.joinChannel(i,(function(){return{tab_id:o,page_url:location.href,page_description:document.title,idle_timeout_seconds:s,visitor_metadata:k.pick(["location"],a),allow_rejection:n&&!u}}),c).take(1).map((function(e){var t=e.phoenixChannel,n=e.leave;return[new U_(t),n]})).subscribe((function(e){var t=g(e,2),n=t[0],i=t[1];u=!0,r(y,{presence:n,leavePresence:i})}),(function(e){k.pathEq(["error","reason"],E,e)?r(v):r(m)}))},T={joinState:c,visitorId:n},x=function e(t,n){var r=g(function(e,t,n){switch(t){case b:switch(e.joinState){case c:return[i(i({},e),{},{joinState:u}),function(t){return S(e.visitorId,!0,t)}];default:return[e]}case _:switch(e.joinState){case c:case f:return[i(i({},e),{},{joinState:p}),function(t){return S(e.visitorId,!1,t)}];case u:return[i(i({},e),{},{joinState:l})];default:return[e]}case v:switch(e.joinState){case l:return[i(i({},e),{},{joinState:p}),function(t){return S(e.visitorId,!1,t)}];case u:return[i(i({},e),{},{joinState:f})];case p:return nm.error("Request to join visitor presence channel was rejected, although we did not allow rejection"),[i(i({},e),{},{joinState:f})];default:return nm.error("Received join rejection while we were not joining channel",{currentState:e}),[e]}case m:switch(e.joinState){case u:case p:case l:return[i(i({},e),{},{joinState:d})];default:return nm.error("Received join error while we were not joining channel",{currentState:e}),[e]}case y:switch(e.joinState){case u:case p:case l:return[i(i({},e),{},{joinState:h,leavePresence:n.leavePresence}),function(){return O.next(n.presence)}];default:return nm.error("Received join successful while we were not joining channel",{currentState:e}),[e]}case w:var r=n;if(r===e.visitorId)return[e];switch(e.joinState){case u:case p:case l:var o=e.joinState===u;return[i(i({},e),{},{visitorId:r}),function(e){return S(r,o,e)}];case h:return[i(i({},e),{},{visitorId:r,joinState:p}),function(t){e.leavePresence(),S(r,!1,t)}];default:return nm.info("Visitor ID changed, but not joining visitor presence"),[e]}default:return nm.error("Received invalid action",{action:t}),[e]}}(T,t,n),2),o=r[0],s=r[1];T=o,s&&s(e)};r.subscribe((function(e){return x(w,e)}),nm.error.bind(nm,"Error from visitor ID subscription in visitor presence channel")),this.requestJoin=function(){x(_)},this.requestJoinAllowRejection=function(){x(b)},this.getPresenceObservable=function(){return O.asObservable()};var A=O.switchMap((function(e){return Gv.Observable.create((function(t){e.onSync((function(){var n=e.list();n[0]?k.any(k.equals(void 0),n[0].metas)?nm.warn("Visitor Presence metas included undefined value"):t.next(n[0].metas):t.next([])}))}))})).publishReplay(1);A=ny(A),this.getSameVisitorConnections=function(){return A}}var nw="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function rw(e,t){return e(t={exports:{}},t.exports),t.exports}var iw=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ow=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],sw=function(e){var t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));for(var i=iw.exec(e||""),o={},s=14;s--;)o[ow[s]]=i[s]||"";return-1!=n&&-1!=r&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o},aw="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":o(e)},cw=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},uw=function(){function e(e,t){for(var n=0;n0)return function(e){if((e=String(e)).length>1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*vw;case"days":case"day":case"d":return n*bw;case"hours":case"hour":case"hrs":case"hr":case"h":return n*dw;case"minutes":case"minute":case"mins":case"min":case"m":return n*hw;case"seconds":case"second":case"secs":case"sec":case"s":return n*fw;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}(e);if("number"===r&&!1===isNaN(e))return t.long?yw(n=e,bw,"day")||yw(n,dw,"hour")||yw(n,hw,"minute")||yw(n,fw,"second")||n+" ms":function(e){if(e>=bw)return Math.round(e/bw)+"d";if(e>=dw)return Math.round(e/dw)+"h";if(e>=hw)return Math.round(e/hw)+"m";if(e>=fw)return Math.round(e/fw)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function yw(e,t,n){if(!(e=31},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())})),ww=sw,Ew=_w("socket.io-client:url"),Ow=function(e,t){var n=e;t=t||nw.location,null==e&&(e=t.protocol+"//"+t.host);"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?t.protocol+e:t.host+e),/^(https?|wss?):\/\//.test(e)||(Ew("protocol-less url %s",e),e=void 0!==t?t.protocol+"//"+e:"https://"+e),Ew("parse %s",e),n=ww(e));n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443"));n.path=n.path||"/";var r=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+r+":"+n.port,n.href=n.protocol+"://"+r+(t&&t.port===n.port?"":":"+n.port),n};var Sw=1e3,Tw=6e4,kw=60*Tw,xw=24*kw,Aw=365.25*xw,Iw=function(e,t){return t=t||{},"string"==typeof e?function(e){if((e=""+e).length>1e4)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*Aw;case"days":case"day":case"d":return n*xw;case"hours":case"hour":case"hrs":case"hr":case"h":return n*kw;case"minutes":case"minute":case"mins":case"min":case"m":return n*Tw;case"seconds":case"second":case"secs":case"sec":case"s":return n*Sw;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}(e):t.long?Nw(n=e,xw,"day")||Nw(n,kw,"hour")||Nw(n,Tw,"minute")||Nw(n,Sw,"second")||n+" ms":function(e){return e>=xw?Math.round(e/xw)+"d":e>=kw?Math.round(e/kw)+"h":e>=Tw?Math.round(e/Tw)+"m":e>=Sw?Math.round(e/Sw)+"s":e+"ms"}(e);var n};function Nw(e,t,n){if(!(e=31},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){return JSON.stringify(e)},t.enable(n())})),Pw=rw((function(e,t){ /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ (function(){var n={function:!0,object:!0},r=n.object&&t&&!t.nodeType&&t,i=n["undefined"==typeof window?"undefined":aw(window)]&&window||this,o=r&&n.object&&e&&!e.nodeType&&"object"==aw(nw)&&nw;function s(e,t){e||(e=i.Object()),t||(t=i.Object());var r=e.Number||i.Number,o=e.String||i.String,a=e.Object||i.Object,c=e.Date||i.Date,u=e.SyntaxError||i.SyntaxError,l=e.TypeError||i.TypeError,p=e.Math||i.Math,f=e.JSON||i.JSON;"object"==(void 0===f?"undefined":aw(f))&&f&&(t.stringify=f.stringify,t.parse=f.parse);var h,d,b,v=a.prototype,m=v.toString,y=new c(-0xc782b5b800cec);try{y=-109252==y.getUTCFullYear()&&0===y.getUTCMonth()&&1===y.getUTCDate()&&10==y.getUTCHours()&&37==y.getUTCMinutes()&&6==y.getUTCSeconds()&&708==y.getUTCMilliseconds()}catch(e){}function g(e){if(g[e]!==b)return g[e];var n;if("bug-string-char-index"==e)n="a"!="a"[0];else if("json"==e)n=g("json-stringify")&&g("json-parse");else{var i,s='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if("json-stringify"==e){var a=t.stringify,u="function"==typeof a&&y;if(u){(i=function(){return 1}).toJSON=i;try{u="0"===a(0)&&"0"===a(new r)&&'""'==a(new o)&&a(m)===b&&a(b)===b&&a()===b&&"1"===a(i)&&"[1]"==a([i])&&"[null]"==a([b])&&"null"==a(null)&&"[null,null,null]"==a([b,m,null])&&a({a:[i,!0,!1,null,"\0\b\n\f\r\t"]})==s&&"1"===a(null,i)&&"[\n 1,\n 2\n]"==a([1,2],null,1)&&'"-271821-04-20T00:00:00.000Z"'==a(new c(-864e13))&&'"+275760-09-13T00:00:00.000Z"'==a(new c(864e13))&&'"-000001-01-01T00:00:00.000Z"'==a(new c(-621987552e5))&&'"1969-12-31T23:59:59.999Z"'==a(new c(-1))}catch(e){u=!1}}n=u}if("json-parse"==e){var l=t.parse;if("function"==typeof l)try{if(0===l("0")&&!l(!1)){var p=5==(i=l(s)).a.length&&1===i.a[0];if(p){try{p=!l('"\t"')}catch(e){}if(p)try{p=1!==l("01")}catch(e){}if(p)try{p=1!==l("1.")}catch(e){}}}}catch(e){p=!1}n=p}}return g[e]=!!n}if(!g("json")){var _="[object Function]",w="[object Number]",E="[object String]",O="[object Array]",S=g("bug-string-char-index");if(!y)var T=p.floor,k=[0,31,59,90,120,151,181,212,243,273,304,334],x=function(e,t){return k[t]+365*(e-1970)+T((e-1969+(t=+(t>1)))/4)-T((e-1901+t)/100)+T((e-1601+t)/400)};if((h=v.hasOwnProperty)||(h=function(e){var t,n={};return(n.__proto__=null,n.__proto__={toString:1},n).toString!=m?h=function(e){var t=this.__proto__,n=e in(this.__proto__=null,this);return this.__proto__=t,n}:(t=n.constructor,h=function(e){var n=(this.constructor||t).prototype;return e in this&&!(e in n&&this[e]===n[e])}),n=null,h.call(this,e)}),d=function(e,t){var r,i,o,s=0;for(o in(r=function(){this.valueOf=0}).prototype.valueOf=0,i=new r)h.call(i,o)&&s++;return r=i=null,s?d=2==s?function(e,t){var n,r={},i=m.call(e)==_;for(n in e)i&&"prototype"==n||h.call(r,n)||!(r[n]=1)||!h.call(e,n)||t(n)}:function(e,t){var n,r,i=m.call(e)==_;for(n in e)i&&"prototype"==n||!h.call(e,n)||(r="constructor"===n)||t(n);(r||h.call(e,n="constructor"))&&t(n)}:(i=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"],d=function(e,t){var r,o,s=m.call(e)==_,a=!s&&"function"!=typeof e.constructor&&n[aw(e.hasOwnProperty)]&&e.hasOwnProperty||h;for(r in e)s&&"prototype"==r||!a.call(e,r)||t(r);for(o=i.length;r=i[--o];a.call(e,r)&&t(r));}),d(e,t)},!g("json-stringify")){var A={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"},I=function(e,t){return("000000"+(t||0)).slice(-e)},N=function(e){for(var t='"',n=0,r=e.length,i=!S||r>10,o=i&&(S?e.split(""):e);n-1/0&&c<1/0){if(x){for(v=T(c/864e5),p=T(v/365.2425)+1970-1;x(p+1,0)<=v;p++);for(f=T((v-x(p,0))/30.42);x(p,f+1)<=v;f++);v=1+v-x(p,f),g=T((y=(c%864e5+864e5)%864e5)/36e5)%24,_=T(y/6e4)%60,S=T(y/1e3)%60,k=y%1e3}else p=c.getUTCFullYear(),f=c.getUTCMonth(),v=c.getUTCDate(),g=c.getUTCHours(),_=c.getUTCMinutes(),S=c.getUTCSeconds(),k=c.getUTCMilliseconds();c=(p<=0||p>=1e4?(p<0?"-":"+")+I(6,p<0?-p:p):I(4,p))+"-"+I(2,f+1)+"-"+I(2,v)+"T"+I(2,g)+":"+I(2,_)+":"+I(2,S)+"."+I(3,k)+"Z"}else c=null;if(r&&(c=r.call(n,t,c)),null===c)return"null";if("[object Boolean]"==(u=m.call(c)))return""+c;if(u==w)return c>-1/0&&c<1/0?""+c:"null";if(u==E)return N(""+c);if("object"==(void 0===c?"undefined":aw(c))){for(P=a.length;P--;)if(a[P]===c)throw l();if(a.push(c),A=[],M=s,s+=o,u==O){for(R=0,P=c.length;R0)for(i="",r>10&&(r=10);i.length=48&&i<=57||i>=97&&i<=102||i>=65&&i<=70||L();e+=M("0x"+o.slice(t,R));break;default:L()}else{if(34==i)break;for(i=o.charCodeAt(R),t=R;i>=32&&92!=i&&34!=i;)i=o.charCodeAt(++R);e+=o.slice(t,R)}if(34==o.charCodeAt(R))return R++,e;L();default:if(t=R,45==i&&(r=!0,i=o.charCodeAt(++R)),i>=48&&i<=57){for(48==i&&((i=o.charCodeAt(R+1))>=48&&i<=57)&&L(),r=!1;R=48&&i<=57);R++);if(46==o.charCodeAt(R)){for(n=++R;n=48&&i<=57);n++);n==R&&L(),R=n}if(101==(i=o.charCodeAt(R))||69==i){for(43!=(i=o.charCodeAt(++R))&&45!=i||R++,n=R;n=48&&i<=57);n++);n==R&&L(),R=n}return+o.slice(t,R)}if(r&&L(),"true"==o.slice(R,R+4))return R+=4,!0;if("false"==o.slice(R,R+5))return R+=5,!1;if("null"==o.slice(R,R+4))return R+=4,null;L()}return"$"},U=function e(t){var n,r;if("$"==t&&L(),"string"==typeof t){if("@"==(S?t.charAt(0):t[0]))return t.slice(1);if("["==t){for(n=[];"]"!=(t=q());r||(r=!0))r&&(","==t?"]"==(t=q())&&L():L()),","==t&&L(),n.push(e(t));return n}if("{"==t){for(n={};"}"!=(t=q());r||(r=!0))r&&(","==t?"}"==(t=q())&&L():L()),","!=t&&"string"==typeof t&&"@"==(S?t.charAt(0):t[0])&&":"==q()||L(),n[t.slice(1)]=e(q());return n}L()}return t},D=function(e,t,n){var r=V(e,t,n);r===b?delete e[t]:e[t]=r},V=function(e,t,n){var r,i=e[t];if("object"==(void 0===i?"undefined":aw(i))&&i)if(m.call(i)==O)for(r=i.length;r--;)D(i,r,n);else d(i,(function(e){D(i,e,n)}));return n.call(e,t,i)};t.parse=function(e,t){var n,r;return R=0,P=""+e,n=U(q()),"$"!=q()&&L(),R=P=null,t&&m.call(t)==_?V(((r={})[""]=n,r),"",t):n}}}return t.runInContext=s,t}if(!o||o.global!==o&&o.window!==o&&o.self!==o||(i=o),r)s(i,r);else{var a=i.JSON,c=i.JSON3,u=!1,l=s(i,i.JSON3={noConflict:function(){return u||(u=!0,i.JSON=a,i.JSON3=c,a=c=null),l}});i.JSON={parse:l.parse,stringify:l.stringify}}}).call(nw)})),Mw=jw;function jw(e){if(e)return function(e){for(var t in jw.prototype)e[t]=jw.prototype[t];return e}(e)}jw.prototype.on=jw.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[e]=this._callbacks[e]||[]).push(t),this},jw.prototype.once=function(e,t){var n=this;function r(){n.off(e,r),t.apply(this,arguments)}return this._callbacks=this._callbacks||{},r.fn=t,this.on(e,r),this},jw.prototype.off=jw.prototype.removeListener=jw.prototype.removeAllListeners=jw.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks[e];if(!r)return this;if(1==arguments.length)return delete this._callbacks[e],this;for(var i=0;ir&&(n=r),t>=r||t>=n||0===r)return new ArrayBuffer(0);for(var i=new Uint8Array(e),o=new Uint8Array(n-t),s=t,a=0;s=55296&&t<=56319&&i>t&63|128)}function f(e){if(0==(4294967168&e))return u(e);var t="";return 0==(4294965248&e)?t=u(e>>6&31|192):0==(4294901760&e)?(t=u(e>>12&15|224),t+=p(e,6)):0==(4292870144&e)&&(t=u(e>>18&7|240),t+=p(e,12),t+=p(e,6)),t+=u(63&e|128)}function h(){if(c>=a)throw Error("Invalid byte index");var e=255&s[c];if(c++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function d(){var e,t;if(c>a)throw Error("Invalid byte index");if(c==a)return!1;if(e=255&s[c],c++,0==(128&e))return e;if(192==(224&e)){if((t=(31&e)<<6|h())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&e)){if((t=(15&e)<<12|h()<<6|h())>=2048)return t;throw Error("Invalid continuation byte")}if(240==(248&e)&&(t=(15&e)<<18|h()<<12|h()<<6|h())>=65536&&t<=1114111)return t;throw Error("Invalid WTF-8 detected")}var b={version:"1.0.0",encode:function(e){for(var t=l(e),n=t.length,r=-1,i="";++r65535&&(i+=u((t-=65536)>>>10&1023|55296),t=56320|1023&t),i+=u(t);return i}(n)}};if(r&&!r.nodeType)if(i)i.exports=b;else{var v={}.hasOwnProperty;for(var m in b)v.call(b,m)&&(r[m]=b[m])}else n.wtf8=b}(nw)})),Xw=rw((function(e,t){!function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(256),r=0;r>2],o+=e[(3&r[n])<<4|r[n+1]>>4],o+=e[(15&r[n+1])<<2|r[n+2]>>6],o+=e[63&r[n+2]];return i%3==2?o=o.substring(0,o.length-1)+"=":i%3==1&&(o=o.substring(0,o.length-2)+"=="),o},t.decode=function(e){var t,r,i,o,s,a=.75*e.length,c=e.length,u=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var l=new ArrayBuffer(a),p=new Uint8Array(l);for(t=0;t>4,p[u++]=(15&i)<<4|o>>2,p[u++]=(3&o)<<6|63&s;return l}}()})),$w=nw.BlobBuilder||nw.WebKitBlobBuilder||nw.MSBlobBuilder||nw.MozBlobBuilder,Zw=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),eE=Zw&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),tE=$w&&$w.prototype.append&&$w.prototype.getBlob;function nE(e){for(var t=0;t1?{type:f[i],data:e.substring(1)}:{type:f[i]}:h}i=new Uint8Array(e)[0];var s=o(e,1);return d&&"blob"===n&&(s=new d([s])),{type:f[i],data:s}},t.decodeBase64Packet=function(e,t){var r=f[e.charAt(0)];if(!n)return{type:r,data:{base64:!0,data:e.substr(1)}};var i=n.decode(e.substr(1));return"blob"===t&&d&&(i=new d([i])),{type:r,data:i}},t.encodePayload=function(e,n,r){"function"==typeof n&&(r=n,n=null);var o=i(e);if(n&&o)return d&&!l?t.encodePayloadAsBlob(e,r):t.encodePayloadAsArrayBuffer(e,r);if(!e.length)return r("0:");b(e,(function(e,r){t.encodePacket(e,!!o&&n,!0,(function(e){r(null,function(e){return e.length+":"+e}(e))}))}),(function(e,t){return r(t.join(""))}))},t.decodePayload=function(e,n,r){if("string"!=typeof e)return t.decodePayloadAsBinary(e,n,r);var i;if("function"==typeof n&&(r=n,n=null),""==e)return r(h,0,1);for(var o,s,a="",c=0,u=e.length;c0;){for(var c=new Uint8Array(i),u=0===c[0],l="",p=1;255!=c[p];p++){if(l.length>310){a=!0;break}l+=c[p]}if(a)return r(h,0,1);i=o(i,2+l.length),l=parseInt(l);var f=o(i,0,l);if(u)try{f=String.fromCharCode.apply(null,new Uint8Array(f))}catch(e){var d=new Uint8Array(f);f="";for(p=0;p0);return t}function gE(){var e=yE(+new Date);return e!==pE?(vE=0,pE=e):e+"."+yE(vE++)}for(;mE<64;mE++)bE[dE[mE]]=mE;gE.encode=yE,gE.decode=function(e){var t=0;for(mE=0;mE';r=document.createElement(e)}catch(e){(r=document.createElement("iframe")).name=n.iframeId,r.src="javascript:0"}r.id=n.iframeId,n.form.appendChild(r),n.iframe=r}this.form.action=this.uri(),c(),e=e.replace(GE,"\\\n"),this.area.value=e.replace(WE,"\\n");try{this.form.submit()}catch(e){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===n.iframe.readyState&&a()}:this.iframe.onload=a};var QE,YE={},KE=Object.freeze({default:YE}),XE=KE&&YE||KE,$E=uE,ZE=sE,eO=fE,tO=hE,nO=_E,rO=_w("engine.io-client:websocket"),iO=nw.WebSocket||nw.MozWebSocket;if("undefined"==typeof window)try{QE=XE}catch(e){}var oO=iO;oO||"undefined"!=typeof window||(oO=QE);var sO=aO;function aO(e){e&&e.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=e.perMessageDeflate,this.usingBrowserWebSocket=iO&&!e.forceNode,this.usingBrowserWebSocket||(oO=QE),$E.call(this,e)}tO(aO,$E),aO.prototype.name="websocket",aO.prototype.supportsBinary=!0,aO.prototype.doOpen=function(){if(this.check()){var e=this.uri(),t={agent:this.agent,perMessageDeflate:this.perMessageDeflate};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(t.headers=this.extraHeaders),this.localAddress&&(t.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket?new oO(e):new oO(e,void 0,t)}catch(e){return this.emit("error",e)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},aO.prototype.addEventListeners=function(){var e=this;this.ws.onopen=function(){e.onOpen()},this.ws.onclose=function(){e.onClose()},this.ws.onmessage=function(t){e.onData(t.data)},this.ws.onerror=function(t){e.onError("websocket error",t)}},aO.prototype.write=function(e){var t=this;this.writable=!1;for(var n=e.length,r=0,i=n;r0&&(this.extraHeaders=t.extraHeaders),t.localAddress&&(this.localAddress=t.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}IO.priorWebsocketSuccess=!1,wO(IO.prototype),IO.protocol=SO.protocol,IO.Socket=IO,IO.Transport=uE,IO.transports=pO,IO.parser=sE,IO.prototype.createTransport=function(e){EO('creating transport "%s"',e);var t=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}(this.query);return t.EIO=SO.protocol,t.transport=e,this.id&&(t.sid=this.id),new _O[e]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:t,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized,perMessageDeflate:this.perMessageDeflate,extraHeaders:this.extraHeaders,forceNode:this.forceNode,localAddress:this.localAddress})},IO.prototype.open=function(){var e;if(this.rememberUpgrade&&IO.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length){var t=this;return void setTimeout((function(){t.emit("error","No transports available")}),0)}e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)},IO.prototype.setTransport=function(e){EO("setting transport %s",e.name);var t=this;this.transport&&(EO("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",(function(){t.onDrain()})).on("packet",(function(e){t.onPacket(e)})).on("error",(function(e){t.onError(e)})).on("close",(function(){t.onClose("transport close")}))},IO.prototype.probe=function(e){EO('probing transport "%s"',e);var t=this.createTransport(e,{probe:1}),n=!1,r=this;function i(){if(r.onlyBinaryUpgrades){var i=!this.supportsBinary&&r.transport.supportsBinary;n=n||i}n||(EO('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(function(i){if(!n)if("pong"===i.type&&"probe"===i.data){if(EO('probe transport "%s" pong',e),r.upgrading=!0,r.emit("upgrading",t),!t)return;IO.priorWebsocketSuccess="websocket"===t.name,EO('pausing current transport "%s"',r.transport.name),r.transport.pause((function(){n||"closed"!==r.readyState&&(EO("changing transport and sending upgrade packet"),l(),r.setTransport(t),t.send([{type:"upgrade"}]),r.emit("upgrade",t),t=null,r.upgrading=!1,r.flush())}))}else{EO('probe transport "%s" failed',e);var o=new Error("probe error");o.transport=t.name,r.emit("upgradeError",o)}})))}function o(){n||(n=!0,l(),t.close(),t=null)}function s(n){var i=new Error("probe error: "+n);i.transport=t.name,o(),EO('probe transport "%s" failed because of error: %s',e,n),r.emit("upgradeError",i)}function a(){s("transport closed")}function c(){s("socket closed")}function u(e){t&&e.name!==t.name&&(EO('"%s" works - aborting "%s"',e.name,t.name),o())}function l(){t.removeListener("open",i),t.removeListener("error",s),t.removeListener("close",a),r.removeListener("close",c),r.removeListener("upgrading",u)}IO.priorWebsocketSuccess=!1,t.once("open",i),t.once("error",s),t.once("close",a),this.once("close",c),this.once("upgrading",u),t.open()},IO.prototype.onOpen=function(){if(EO("socket open"),this.readyState="open",IO.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){EO("starting upgrade probes");for(var e=0,t=this.upgrades.length;e0&&e.jitter<=1?e.jitter:0,this.attempts=0}DO.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-n:e+n}return 0|Math.min(e,this.max)},DO.prototype.reset=function(){this.attempts=0},DO.prototype.setMin=function(e){this.ms=e},DO.prototype.setMax=function(e){this.max=e},DO.prototype.setJitter=function(e){this.jitter=e};var VO=RO,FO=qO,BO=aE,HO=Fw,WO=MO,GO=LO,zO=_w("socket.io-client:manager"),JO=hO,QO=UO,YO=Object.prototype.hasOwnProperty,KO=XO;function XO(e,t){if(!(this instanceof XO))return new XO(e,t);e&&"object"===(void 0===e?"undefined":aw(e))&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.nsps={},this.subs=[],this.opts=t,this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor||.5),this.backoff=new QO({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this.readyState="closed",this.uri=e,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[],this.encoder=new HO.Encoder,this.decoder=new HO.Decoder,this.autoConnect=!1!==t.autoConnect,this.autoConnect&&this.open()}XO.prototype.emitAll=function(){for(var e in this.emit.apply(this,arguments),this.nsps)YO.call(this.nsps,e)&&this.nsps[e].emit.apply(this.nsps[e],arguments)},XO.prototype.updateSocketIds=function(){for(var e in this.nsps)YO.call(this.nsps,e)&&(this.nsps[e].id=this.engine.id)},BO(XO.prototype),XO.prototype.reconnection=function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection},XO.prototype.reconnectionAttempts=function(e){return arguments.length?(this._reconnectionAttempts=e,this):this._reconnectionAttempts},XO.prototype.reconnectionDelay=function(e){return arguments.length?(this._reconnectionDelay=e,this.backoff&&this.backoff.setMin(e),this):this._reconnectionDelay},XO.prototype.randomizationFactor=function(e){return arguments.length?(this._randomizationFactor=e,this.backoff&&this.backoff.setJitter(e),this):this._randomizationFactor},XO.prototype.reconnectionDelayMax=function(e){return arguments.length?(this._reconnectionDelayMax=e,this.backoff&&this.backoff.setMax(e),this):this._reconnectionDelayMax},XO.prototype.timeout=function(e){return arguments.length?(this._timeout=e,this):this._timeout},XO.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},XO.prototype.open=XO.prototype.connect=function(e,t){if(zO("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;zO("opening %s",this.uri),this.engine=VO(this.uri,this.opts);var n=this.engine,r=this;this.readyState="opening",this.skipReconnect=!1;var i=WO(n,"open",(function(){r.onopen(),e&&e()})),o=WO(n,"error",(function(t){if(zO("connect_error"),r.cleanup(),r.readyState="closed",r.emitAll("connect_error",t),e){var n=new Error("Connection error");n.data=t,e(n)}else r.maybeReconnectOnOpen()}));if(!1!==this._timeout){var s=this._timeout;zO("connect attempt will timeout after %d",s);var a=setTimeout((function(){zO("connect attempt timed out after %d",s),i.destroy(),n.close(),n.emit("error","timeout"),r.emitAll("connect_timeout",s)}),s);this.subs.push({destroy:function(){clearTimeout(a)}})}return this.subs.push(i),this.subs.push(o),this},XO.prototype.onopen=function(){zO("open"),this.cleanup(),this.readyState="open",this.emit("open");var e=this.engine;this.subs.push(WO(e,"data",GO(this,"ondata"))),this.subs.push(WO(e,"ping",GO(this,"onping"))),this.subs.push(WO(e,"pong",GO(this,"onpong"))),this.subs.push(WO(e,"error",GO(this,"onerror"))),this.subs.push(WO(e,"close",GO(this,"onclose"))),this.subs.push(WO(this.decoder,"decoded",GO(this,"ondecoded")))},XO.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},XO.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},XO.prototype.ondata=function(e){this.decoder.add(e)},XO.prototype.ondecoded=function(e){this.emit("packet",e)},XO.prototype.onerror=function(e){zO("error",e),this.emitAll("error",e)},XO.prototype.socket=function(e,t){var n=this.nsps[e];if(!n){n=new FO(this,e,t),this.nsps[e]=n;var r=this;n.on("connecting",i),n.on("connect",(function(){n.id=r.engine.id})),this.autoConnect&&i()}function i(){~JO(r.connecting,n)||r.connecting.push(n)}return n},XO.prototype.destroy=function(e){var t=JO(this.connecting,e);~t&&this.connecting.splice(t,1),this.connecting.length||this.close()},XO.prototype.packet=function(e){zO("writing packet %j",e);var t=this;e.query&&0===e.type&&(e.nsp+="?"+e.query),t.encoding?t.packetBuffer.push(e):(t.encoding=!0,this.encoder.encode(e,(function(n){for(var r=0;r0&&!this.encoding){var e=this.packetBuffer.shift();this.packet(e)}},XO.prototype.cleanup=function(){zO("cleanup");for(var e=this.subs.length,t=0;t=this._reconnectionAttempts)zO("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var t=this.backoff.duration();zO("will wait %dms before reconnect attempt",t),this.reconnecting=!0;var n=setTimeout((function(){e.skipReconnect||(zO("attempting reconnect"),e.emitAll("reconnect_attempt",e.backoff.attempts),e.emitAll("reconnecting",e.backoff.attempts),e.skipReconnect||e.open((function(t){t?(zO("reconnect attempt error"),e.reconnecting=!1,e.reconnect(),e.emitAll("reconnect_error",t.data)):(zO("reconnect success"),e.onreconnect())})))}),t);this.subs.push({destroy:function(){clearTimeout(n)}})}},XO.prototype.onreconnect=function(){var e=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",e)};var $O=rw((function(e,t){var n=Ow,r=Fw,i=KO,o=_w("socket.io-client");e.exports=t=a;var s=t.managers={};function a(e,t){"object"===(void 0===e?"undefined":aw(e))&&(t=e,e=void 0),t=t||{};var r,a=n(e),c=a.source,u=a.id,l=a.path,p=s[u]&&l in s[u].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||p?(o("ignoring socket cache for %s",c),r=i(c,t)):(s[u]||(o("new io instance for %s",c),s[u]=i(c,t)),r=s[u]),a.query&&!t.query?t.query=a.query:t&&"object"===aw(t.query)&&(t.query=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")}(t.query)),r.socket(a.path,t)}t.protocol=r.protocol,t.connect=a,t.Manager=KO,t.Socket=qO})),ZO=function(e,t){return void 0===t?e:t},eS=function(){function e(){cw(this,e)}return uw(e,null,[{key:"establish",value:function(e){var t=e.url,n=e.id,r=e.isActiveTab,i=e.options;e.logger.info("Establishing Kluster connection via Channel lib;");var o=function(e,t){return e+(e.split("?")[1]?"&":"?")+t}(t,"id="+n+"&tags="+function(e){var t=e?[{name:"cobrowse",unique:!0}]:[];return encodeURIComponent(JSON.stringify(t))}(r));return $O.connect(o,{"force new connection":!0,timeout:ZO(15e3,i.timeout),reconnectionDelay:ZO(1e3,i.reconnectionDelay),reconnectionDelayMax:ZO(1e3,i.reconnectionDelayMax),randomizationFactor:ZO(0,i.randomizationFactor),reconnectionAttempts:ZO(Infinity,i.reconnectionAttempts),upgrade:ZO(undefined,i.upgrade)})}}]),e}(),tS=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];cw(this,e),this.emit=this.emit.bind(this),this.socket=t,this.stopped=null===this.socket,this.tags=n,this.childEmitters=[]}return uw(e,[{key:"stop",value:function(){return this.stopped=!0,this.socket=null,this.childEmitters.map((function(e){return e.stop()}))}},{key:"in",value:function(e){var t=new this.constructor(this.socket,[e],this);return this.childEmitters.push(t),t}},{key:"emit",value:function(e,t){if(!this.stopped){var n={"channel:event_name":e,"channel:event_data":t,"channel:tags":this.tags};return this.socket.emit("announce",n)}}},{key:"authorize",value:function(e){if(!this.stopped)return this.socket.emit("authorize",{token:e})}}]),e}(),nS=function(){function e(t){var n=t.id,r=t.socketId,i=t.tags;cw(this,e),this.id=n,this.socketId=r,this.tags=i}return uw(e,null,[{key:"build",value:function(t){var n=t.tags.map((function(e){return e._name}));return new e({id:t.id,socketId:t.socketId,tags:n})}}]),e}(),rS=function(e){if("function"==typeof e)return e;return function(){return e}},iS="undefined"!=typeof self?self:null,oS="undefined"!=typeof window?window:null,sS=iS||oS||sS,aS="2.0.0",cS=0,uS=1,lS=2,pS=3,fS="closed",hS="errored",dS="joined",bS="joining",vS="leaving",mS="phx_close",yS="phx_error",gS="phx_join",_S="phx_reply",wS="phx_leave",ES="longpoll",OS="websocket",SS=4,TS=function(){function e(t,n,r,i){cw(this,e),this.channel=t,this.event=n,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=i,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}return uw(e,[{key:"resend",value:function(e){this.timeout=e,this.reset(),this.send()}},{key:"send",value:function(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}},{key:"receive",value:function(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}},{key:"reset",value:function(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}},{key:"matchReceive",value:function(e){var t=e.status,n=e.response;e._ref;this.recHooks.filter((function(e){return e.status===t})).forEach((function(e){return e.callback(n)}))}},{key:"cancelRefEvent",value:function(){this.refEvent&&this.channel.off(this.refEvent)}},{key:"cancelTimeout",value:function(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}},{key:"startTimeout",value:function(){var e=this;this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(function(t){e.cancelRefEvent(),e.cancelTimeout(),e.receivedResp=t,e.matchReceive(t)})),this.timeoutTimer=setTimeout((function(){e.trigger("timeout",{})}),this.timeout)}},{key:"hasReceived",value:function(e){return this.receivedResp&&this.receivedResp.status===e}},{key:"trigger",value:function(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}}]),e}(),kS=function(){function e(t,n){cw(this,e),this.callback=t,this.timerCalc=n,this.timer=null,this.tries=0}return uw(e,[{key:"reset",value:function(){this.tries=0,clearTimeout(this.timer)}},{key:"scheduleTimeout",value:function(){var e=this;clearTimeout(this.timer),this.timer=setTimeout((function(){e.tries=e.tries+1,e.callback()}),this.timerCalc(this.tries+1))}}]),e}(),xS=function(){function e(t,n,r){var i=this;cw(this,e),this.state=fS,this.topic=t,this.params=rS(n||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new TS(this,gS,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new kS((function(){i.socket.isConnected()&&i.rejoin()}),this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError((function(){return i.rejoinTimer.reset()}))),this.stateChangeRefs.push(this.socket.onOpen((function(){i.rejoinTimer.reset(),i.isErrored()&&i.rejoin()}))),this.joinPush.receive("ok",(function(){i.state=dS,i.rejoinTimer.reset(),i.pushBuffer.forEach((function(e){return e.send()})),i.pushBuffer=[]})),this.joinPush.receive("error",(function(){i.state=hS,i.socket.isConnected()&&i.rejoinTimer.scheduleTimeout()})),this.onClose((function(){i.rejoinTimer.reset(),i.socket.hasLogger()&&i.socket.log("channel","close "+i.topic+" "+i.joinRef()),i.state=fS,i.socket.remove(i)})),this.onError((function(e){i.socket.hasLogger()&&i.socket.log("channel","error "+i.topic,e),i.isJoining()&&i.joinPush.reset(),i.state=hS,i.socket.isConnected()&&i.rejoinTimer.scheduleTimeout()})),this.joinPush.receive("timeout",(function(){i.socket.hasLogger()&&i.socket.log("channel","timeout "+i.topic+" ("+i.joinRef()+")",i.joinPush.timeout),new TS(i,wS,rS({}),i.timeout).send(),i.state=hS,i.joinPush.reset(),i.socket.isConnected()&&i.rejoinTimer.scheduleTimeout()})),this.on(_S,(function(e,t){i.trigger(i.replyEventName(t),e)}))}return uw(e,[{key:"join",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}},{key:"onClose",value:function(e){this.on(mS,e)}},{key:"onError",value:function(e){return this.on(yS,(function(t){return e(t)}))}},{key:"on",value:function(e,t){var n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}},{key:"off",value:function(e,t){this.bindings=this.bindings.filter((function(n){return!(n.event===e&&(void 0===t||t===n.ref))}))}},{key:"canPush",value:function(){return this.socket.isConnected()&&this.isJoined()}},{key:"push",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.timeout;if(t=t||{},!this.joinedOnce)throw new Error("tried to push '"+e+"' to '"+this.topic+"' before joining. Use channel.join() before pushing events");var r=new TS(this,e,(function(){return t}),n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}},{key:"leave",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=vS;var n=function(){e.socket.hasLogger()&&e.socket.log("channel","leave "+e.topic),e.trigger(mS,"leave")},r=new TS(this,wS,rS({}),t);return r.receive("ok",(function(){return n()})).receive("timeout",(function(){return n()})),r.send(),this.canPush()||r.trigger("ok",{}),r}},{key:"onMessage",value:function(e,t,n){return t}},{key:"isMember",value:function(e,t,n,r){return this.topic===e&&(!r||r===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:n,joinRef:r}),!1))}},{key:"joinRef",value:function(){return this.joinPush.ref}},{key:"rejoin",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.timeout;this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=bS,this.joinPush.resend(e))}},{key:"trigger",value:function(e,t,n,r){var i=this.onMessage(e,t,n,r);if(t&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");for(var o=this.bindings.filter((function(t){return t.event===e})),s=0;s1&&void 0!==arguments[1]?arguments[1]:{};cw(this,e);var i=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(i.state,(function(t){var r=n.caller,i=r.onJoin,o=r.onLeave,s=r.onSync;n.joinRef=n.channel.joinRef(),n.state=e.syncState(n.state,t,i,o),n.pendingDiffs.forEach((function(t){n.state=e.syncDiff(n.state,t,i,o)})),n.pendingDiffs=[],s()})),this.channel.on(i.diff,(function(t){var r=n.caller,i=r.onJoin,o=r.onLeave,s=r.onSync;n.inPendingSyncState()?n.pendingDiffs.push(t):(n.state=e.syncDiff(n.state,t,i,o),s())}))}return uw(e,[{key:"onJoin",value:function(e){this.caller.onJoin=e}},{key:"onLeave",value:function(e){this.caller.onLeave=e}},{key:"onSync",value:function(e){this.caller.onSync=e}},{key:"list",value:function(t){return e.list(this.state,t)}},{key:"inPendingSyncState",value:function(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}}],[{key:"syncState",value:function(e,t,n,r){var i=this,o=this.clone(e),s={},a={};return this.map(o,(function(e,n){t[e]||(a[e]=n)})),this.map(t,(function(e,t){var n=o[e];if(n){var r=t.metas.map((function(e){return e.phx_ref})),c=n.metas.map((function(e){return e.phx_ref})),u=t.metas.filter((function(e){return c.indexOf(e.phx_ref)<0})),l=n.metas.filter((function(e){return r.indexOf(e.phx_ref)<0}));u.length>0&&(s[e]=t,s[e].metas=u),l.length>0&&(a[e]=i.clone(n),a[e].metas=l)}else s[e]=t})),this.syncDiff(o,{joins:s,leaves:a},n,r)}},{key:"syncDiff",value:function(e,t,n,r){var i=this,o=this.clone(t),s=o.joins,a=o.leaves;return n||(n=function(){}),r||(r=function(){}),this.map(s,(function(t,r){var o=e[t];if(e[t]=i.clone(r),o){var s,a=e[t].metas.map((function(e){return e.phx_ref})),c=o.metas.filter((function(e){return a.indexOf(e.phx_ref)<0}));(s=e[t].metas).unshift.apply(s,function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t1&&void 0!==arguments[1]?arguments[1]:{};cw(this,e),this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=r.timeout||1e4,this.transport=r.transport||sS.WebSocket||IS,this.establishedConnections=0,this.defaultEncoder=CS.encode.bind(CS),this.defaultDecoder=CS.decode.bind(CS),this.closeWasClean=!1,this.binaryType=r.binaryType||"arraybuffer",this.connectClock=1,this.transport!==IS?(this.encode=r.encode||this.defaultEncoder,this.decode=r.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);var i=null;oS&&oS.addEventListener&&(oS.addEventListener("pagehide",(function(e){n.conn&&(n.disconnect(),i=n.connectClock)})),oS.addEventListener("pageshow",(function(e){i===n.connectClock&&(i=null,n.connect())}))),this.heartbeatIntervalMs=r.heartbeatIntervalMs||3e4,this.rejoinAfterMs=function(e){return r.rejoinAfterMs?r.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4},this.reconnectAfterMs=function(e){return r.reconnectAfterMs?r.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3},this.logger=r.logger||null,this.longpollerTimeout=r.longpollerTimeout||2e4,this.params=rS(r.params||{}),this.endPoint=t+"/"+OS,this.vsn=r.vsn||aS,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new kS((function(){n.teardown((function(){return n.connect()}))}),this.reconnectAfterMs)}return uw(e,[{key:"replaceTransport",value:function(e){this.disconnect(),this.transport=e}},{key:"protocol",value:function(){return location.protocol.match(/^https/)?"wss":"ws"}},{key:"endPointURL",value:function(){var e=AS.appendParams(AS.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?this.protocol()+":"+e:this.protocol()+"://"+location.host+e}},{key:"disconnect",value:function(e,t,n){this.connectClock++,this.closeWasClean=!0,this.reconnectTimer.reset(),this.teardown(e,t,n)}},{key:"connect",value:function(e){var t=this;this.connectClock++,e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=rS(e)),this.conn||(this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=function(){return t.onConnOpen()},this.conn.onerror=function(e){return t.onConnError(e)},this.conn.onmessage=function(e){return t.onConnMessage(e)},this.conn.onclose=function(e){return t.onConnClose(e)})}},{key:"log",value:function(e,t,n){this.logger(e,t,n)}},{key:"hasLogger",value:function(){return null!==this.logger}},{key:"onOpen",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}},{key:"onClose",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}},{key:"onError",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}},{key:"onMessage",value:function(e){var t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}},{key:"onConnOpen",value:function(){this.hasLogger()&&this.log("transport","connected to "+this.endPointURL()),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach((function(e){return(0,pw(e,2)[1])()}))}},{key:"heartbeatTimeout",value:function(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.abnormalClose("heartbeat timeout"))}},{key:"resetHeartbeat",value:function(){var e=this;this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,clearTimeout(this.heartbeatTimer),setTimeout((function(){return e.sendHeartbeat()}),this.heartbeatIntervalMs))}},{key:"teardown",value:function(e,t,n){var r=this;if(!this.conn)return e&&e();this.waitForBufferDone((function(){r.conn&&(t?r.conn.close(t,n||""):r.conn.close()),r.waitForSocketClosed((function(){r.conn&&(r.conn.onclose=function(){},r.conn=null),e&&e()}))}))}},{key:"waitForBufferDone",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;5!==n&&this.conn&&this.conn.bufferedAmount?setTimeout((function(){t.waitForBufferDone(e,n+1)}),150*n):e()}},{key:"waitForSocketClosed",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;5!==n&&this.conn&&this.conn.readyState!==pS?setTimeout((function(){t.waitForSocketClosed(e,n+1)}),150*n):e()}},{key:"onConnClose",value:function(e){var t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),clearTimeout(this.heartbeatTimer),this.closeWasClean||1e3===t||this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((function(t){return(0,pw(t,2)[1])(e)}))}},{key:"onConnError",value:function(e){this.hasLogger()&&this.log("transport",e);var t=this.transport,n=this.establishedConnections;this.stateChangeCallbacks.error.forEach((function(r){(0,pw(r,2)[1])(e,t,n)})),(t===this.transport||n>0)&&this.triggerChanError()}},{key:"triggerChanError",value:function(){this.channels.forEach((function(e){e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(yS)}))}},{key:"connectionState",value:function(){switch(this.conn&&this.conn.readyState){case cS:return"connecting";case uS:return"open";case lS:return"closing";default:return"closed"}}},{key:"isConnected",value:function(){return"open"===this.connectionState()}},{key:"remove",value:function(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((function(t){return t.joinRef()!==e.joinRef()}))}},{key:"off",value:function(e){for(var t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter((function(t){var n=pw(t,1)[0];return-1===e.indexOf(n)}))}},{key:"channel",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=new xS(e,t,this);return this.channels.push(n),n}},{key:"push",value:function(e){var t=this;if(this.hasLogger()){var n=e.topic,r=e.event,i=e.payload,o=e.ref,s=e.join_ref;this.log("push",n+" "+r+" ("+s+", "+o+")",i)}this.isConnected()?this.encode(e,(function(e){return t.conn.send(e)})):this.sendBuffer.push((function(){return t.encode(e,(function(e){return t.conn.send(e)}))}))}},{key:"makeRef",value:function(){var e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}},{key:"sendHeartbeat",value:function(){var e=this;this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimer=setTimeout((function(){return e.heartbeatTimeout()}),this.heartbeatIntervalMs))}},{key:"abnormalClose",value:function(e){this.closeWasClean=!1,this.isConnected()&&this.conn.close(1e3,e)}},{key:"flushSendBuffer",value:function(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((function(e){return e()})),this.sendBuffer=[])}},{key:"onConnMessage",value:function(e){var t=this;this.decode(e.data,(function(e){var n=e.topic,r=e.event,i=e.payload,o=e.ref,s=e.join_ref;o&&o===t.pendingHeartbeatRef&&(clearTimeout(t.heartbeatTimer),t.pendingHeartbeatRef=null,setTimeout((function(){return t.sendHeartbeat()}),t.heartbeatIntervalMs)),t.hasLogger()&&t.log("receive",(i.status||"")+" "+n+" "+r+" "+(o&&"("+o+")"||""),i);for(var a=0;a0&&!t.onlyLongPollEnabled){var n=setInterval((function(){if("open"===e.connectionState()&&e.transport===IS){var n=PS(e,t);if(e.transport!==n)return e.transport=n,e.disconnect((function(){return e.connect()}))}}),t.avoidLongPollWorkerInterval);return function(){return clearInterval(n)}}}(e,t)}},selectNewTransport:function(n){MS(n)&&MS(i)||(e.transport=PS(e,t),i=n)},stop:function(){n&&n()}}}var LS=function(){return"hidden"===document.visibilityState},qS=function(){return window.navigator.onLine},US=function(e){return"object"===(void 0===e?"undefined":aw(e))?e&&e.reason:e},DS=function(e){for(var t=[],n=0;n3&&void 0!==arguments[3]?arguments[3]:{logPrefix:"PubSub"},i=r.logPrefix,o=0,s=!1;n=n||BS;var a=function(e){n.metrics.connectionMetric&&n.increment(n.metrics.connectionMetric,e)},c=function(t){var n={transport:VS(e.transport),online:qS(),visibility_state:document.visibilityState,error_count:o};return lw({},n,t)},u=function(t,n){return["transport:"+((n||{}).transport||VS(e.transport)),"online:"+qS()].concat(t)},l=function(){s=!0,a(u(["action:connected"])),t.info(i+" socket opened",c({}))},p=function(e){if(e){var n=VS(window.WebSocket),r=c({reason:e.reason,type:e.type,code:e.code&&e.code.toString(),transport:n}),o=u(["action:disconnected","type:"+e.type,"code:"+e.code],{transport:n});e.wasClean?(a(o.concat(["reason:closed"])),t.info(i+" connection disconnected cleanly",r)):LS()?(a(o.concat(["reason:closed"])),t.info(i+" connection disconnected while tab was hidden",r)):(a(o.concat(["reason:closed"])),t.info(i+" connection disconnected",r))}else{var s=VS(IS),l=c({reason:"unknown",type:"unknown",code:"unknown",transport:s}),p=u(["action:disconnected","type:unknown","reason:unknown","code:unknown"],{transport:s});a(p),t.info(i+" connection disconnected",l)}},f=function(e){var n=e&&e.type||"unknown";o+=1;var r=e&&e.target?c({type:n}):c({type:n,error:e});LS()?t.info(i+" connection error while tab was hidden",r):qS()?1!==o||s?(a(u(["action:error"])),t.warn(i+" socket connection error",r)):t.info(i+" socket connection error while attempting to establish the connection first time",r):t.info(i+" connection error while user was offline",r)},h=function(n){return t.info(i+" failed to connect with initial transport",{new_transport:VS(e.transport),error:FS(n)})},d=function(){return a(u(["action:connect"]))};return{onOpen:l,onClose:p,onError:f,onInitialTry:d,onInitialConnectError:h}}var WS=function(e,t){var n=t.enabled,r=t.logPrefix;return n?function(t,n,i){return e.info(r+" "+t+": "+n,{pubsub_data:i})}:function(){}},GS="[Channel Phoenix]",zS={initialDelay:500,maxDelay:1e4,factor:1.2};function JS(e){var t=e.logger,n=e.serverURL,r=e.phoenixLogsEnabled,i=e.getAccessToken,o=e.transport,s=e.socketOverride,a=function(e){var t=e.initialDelay,n=e.maxDelay,r=e.factor,i=e.jitter,o=e.random;n||(n=6e4),void 0===r&&(r=2),void 0===i&&(i=.5),o||(o=Math.random);var s=null,a=function(e){var a=t*Math.pow(r,e);s&&(a=Math.max(a,s),s=null);var c=o(),u=Math.floor(c*i*a),l=Math.floor(10*c)%2==0?a-u:a+u;return Math.min(l,n)};return a.setNextDelayMinimum=function(e){s=e},a.maximizeNextDelay=function(){return a.setNextDelayMinimum(n)},a}(zS),c=n.split("?")[0],u={logger:WS(t,{enabled:r,logPrefix:GS}),params:function(){return{access_token:i()}},reconnectAfterMs:a,timeout:864e5,transport:o};o&&o.customSerializer&&(u.decode=o.decode,u.encode=o.encode);var l=s||new RS("wss://"+c,u),p=new jS(l),f=new HS(l,t,null,{logPrefix:GS});l.onOpen((function(){f.onOpen()})),l.onClose((function(e){f.onClose(e),1e3!==e.code||l.closeWasClean||(t.info(GS+" Detected an abrupt close with code 1000, reconnecting explicitly"),l.conn=null,l.connect())})),l.onError((function(e){if(e&&e.status)switch(e.status){case 403:t.info(GS+" Detected likely pubsub authentication error, reconnecting after max delay"),a.setNextDelayMinimum(zS.maxDelay);break;case 503:var n=zS.maxDelay/2;t.info(GS+" PubSub unavailable, postponing reconnecting for at least "+n+" ms"),a.setNextDelayMinimum(n);break;default:return t.error(GS+" Received unhandled pubsub error status "+e.status+", stopping reconnecting"),void l.disconnect()}f.onError(e),p.selectNewTransport(e)}));var h=void 0,d=function(e){var n=e.checkInterval,r=e.cutoff,i=Date.now();clearInterval(h),h=setInterval((function(){if(l.channels.length>0)i=Date.now();else{var e=Date.now()-i;e>=r&&(t.info(GS+" Disconnecting from PubSub due to idle",{idle_for:e}),l.disconnect(),clearInterval(h))}}),n||6e4)};return{connect:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};p.ensureConnected({onInitialTry:function(){return f.onInitialTry},onInitialError:function(e){return f.onInitialConnectError(e)}}),l.connect(),e.idleDisconnectCutoff>0&&d({checkInterval:e.idleCheckInterval,cutoff:e.idleDisconnectCutoff})},disconnect:l.disconnect.bind(l),channel:l.channel.bind(l),socket:l}}var QS="phoenix_signaler.proxy_channel",YS=function(e){return lw({},e,{event:"phx_reply",payload:{response:{},status:"ok"}})};function KS(e,t){var n=this;this.skipHeartbeat=!0,this.readyState=1,setTimeout((function(){return n.onopen()})),e.onmessage=function(e){n.onmessage(e)},this.send=function(t){e.postMessage(t)},this.close=function(){}}var XS=function(e){var t=KS.bind(null,e);return t.customSerializer=!0,t.decode=function(e,t){return t(e)},t.encode=function(e,t){return t(e)},t};function $S(){var e=void 0;return{listenForProxyTransport:function(t){var n=t.logger,r=t.allowedOrigin,i=t.checkOrigin;i=i||function(e){return e===r};var o=function(t){if(t.source===window.parent&&t.data===QS)if(i(t.origin)){var r=t.ports[0];e=XS(r)}else n.warn("Received CrossFrameMultiplexer message from unexpected origin, discarding",{origin:t.origin})};window.addEventListener("message",o);return function(){return window.removeEventListener("message",o)}},getProxyTransport:function(){return e},createProxyTransport:XS}}function ZS(){return{proxyTo:function(e){var t=e.allowedDomain,n=e.phoenixSocket,r=e.iFrame,i=e.logger,o=new MessageChannel,s={},a={},c=[];o.port1.onmessage=function(e){var t=e.data,r=t.topic,u=t.event,l=t.join_ref,p=t.ref;if("phx_join"===u){s[r]={innerJoinRef:l};var f=function(e,t){return e.channels.find((function(e){return e.topic===t&&(e.isJoined()||e.isJoining())}))}(n,r);if(f)return s[r].channel=f,void o.port1.postMessage(YS(e.data));var h=n.channel(r);return h.join().receive("ok",(function(){o.port1.postMessage(YS(e.data))})).receive("error",(function(e){i.warn("Failed to join extra channel in proxy transport",{topic:r,error:e})})),c.push(h),void(s[r].channel=h)}if("phx_leave"!==u){var d=n.makeRef();a[d]=p,e.data.ref=d,e.data.join_ref=s[r].channel.joinRef(),n.push(e.data)}else{if(s[r]){var b=s[r].channel;-1!==c.indexOf(b)&&(c.splice(c.indexOf(b),1),b.leave()),delete s[r]}else i.warn("Got leave instruction for an unknown channel from inner multiplexer",{topic:r});o.port1.postMessage(YS(e.data))}},r.contentWindow.postMessage(QS,t,[o.port2]);var u=n.onMessage((function(e){var t=e.topic,n=e.event,r=e.payload,i=e.ref;if(s[t]&&(!i||a[i])){var c=i&&a[i];o.port1.postMessage({topic:t,event:n,payload:r,ref:c,join_ref:s[t].innerJoinRef})}}));return function(){c.forEach((function(e){return e.leave()})),n.off([u]),o.port1.close()}}}}var eT=void 0,tT=new function(){return{asInner:new $S,asOuter:new ZS}},nT=function(e){if(e)return[{name:"cobrowse",unique:!0}]},rT=function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=function(e,i){var o={0:e,1:i};r.length>0&&(o[2]=r),t.push("send",o).receive("error",(function(r){t.isClosed()||n.warn("Failed to push channel message",{eventName:e,error:r})})).receive("timeout",(function(){t.isClosed()||n.warn("Failed to push channel message due to timeout",{eventName:e})}))},o=function(i){return e(t,n,r.concat([i]))};return{emit:i,toTag:o}},iT=function(e,t,n){var r={},i=!1;return{on:function(o,s){if(i)t.warn("Tried to add eventHandler to stopped channel",{topic:n,eventName:o});else{var a=e.on(o,function(e){return function(t){t&&t.__value?e(t.__value):e(t)}}(s));!function(e,t,n){r[e]=r[e]||[],r[e].push({handler:t,ref:n})}(o,s,a)}},off:function(t,n){var i=function(e,t){var n=(r[e]||[]).filter((function(e){return e.handler===t}));return 1===n.length?(r[e]=r[e].filter((function(e){return e.handler!==t})),n[0].ref):null}(t,n);i&&e.off(t,i)},stop:function(){i=!0,r={}}}};function oT(e){var t=e.url,n=e.getAccessToken,r=e.isActiveTab,i=e.logger,o=e.callback,s=e.clientOverride,a=eT,c=tT.asInner.getProxyTransport();a||(a=s||new JS({logger:i,serverURL:t,phoenixLogsEnabled:!1,getAccessToken:n,transport:c}),eT=a);var u=[],l=!1,p=function(e){try{return e.split("?")[1].match(/topic=([^&]+)/)[1]}catch(e){throw new Error("Cannot find topic in channel URL params")}}(t),f=a.channel(p,(function(){return{tags:nT(r)}})),h=rT(f,i),d=iT(f,i,p),b=function(e){var t=[],n=new NS(e),r=function(e,t){return t.metas.map((function(t){return new nS({id:e.match(/visitor/)?"visitor":e,socketId:t.connection_id,tags:t.tags.map((function(e){return e.name}))})}))},i=DS(n.list(r));return n.onSync((function(){i=DS(n.list(r)),t.forEach((function(e){return e(i)}))})),{onParticipantState:function(e){return t.push(e),e(i),function(){t=t.filter((function(t){return t!==e}))}}}}(f).onParticipantState,v=function(){f.leave(),u.forEach((function(e){return e.call()})),u=[],d.stop(),l=!0},m=function(e){var t=e.name,n=e.unique?[{name:t,unique:!0}]:[{name:t}];f.push("register_tags",n).receive("error",(function(e){i.warn("Failed to register tag",{error:e,tag_name:t})})).receive("timeout",(function(){i.warn("Failed to register tag due to timeout",{tag_name:t})}))},y={url:t,on:d.on,off:d.off,onParticipantState:b,emit:h.emit,emitAll:h.emit,toTag:h.toTag,registerTag:m,registerUniqueTag:function(e){var t=e.name;m({name:t,unique:!0})},authorize:function(){},proxyToIframe:function(e,t){return tT.asOuter.proxyTo({allowedDomain:t,phoenixSocket:f.socket,logger:i,iFrame:e})},close:v,destroy:v,addDestroyListener:function(e){u.push(e)},isStopped:function(){return l}};return{start:function(){a.connect({idleDisconnectCutoff:3e5});var e=void 0,t=!1;f.join().receive("ok",(function(){t||o(null,y),t=!0})).receive("error",(function(t){t&&"join crashed"===t.reason?i.info("Joining engagement channel failed with crash, retrying",{topic:p}):"unauthorized"===t&&(!e||e1&&void 0!==arguments[1]?arguments[1]:lT,c=s.withTags(["protocol:websocket"]).instrument({namespace:"join-channel"}).attempted(),u={operator_id:r,channel_url:i,is_active_tab:t};nm.log("".concat(yT,": Channel join started"),u);var l=new Promise((function(e,r){var s={timeout:3e4,reconnectionDelay:2e3,reconnectionDelayMax:3e3,randomizationFactor:.5,reconnectionAttempts:15,upgrade:!0};a.join({url:i,id:n,isInitiallyActive:t,options:s,getAccessToken:o,logger:nm,callback:function(t,n){t?(nm.warn("".concat(yT,": Channel join failed"),k.merge(u,{error:t})),c.failed(),r(t)):(n.authorize(o),nm.info("".concat(yT,": Channel join succeeded"),u),c.succeeded(),n.observable=function(e){return $m(n,e)},e(n))}})}));return vT(r,i,l),Gv.Observable.fromPromise(l)},_T=["scroll","keyup","mousemove"];function wT(e){var t=e.getAccessToken,n=e.stats,r=e.start,i=e.stop,o=e.hideMouse,s=e.createChannelObservable,a=e.dynamicImport;s||(s=gT),a||(a=dm);var c=r.distinctUntilChanged().switchMap((function(e){return s({channelUrl:e,participantId:"source",isActiveTab:!0,getAccessToken:t,stats:n})})).publishReplay(1).refCount();this.sourceObservable=c.flatMap((function(e){return a("Cobra").map((function(t){return{Cobra:t,channel:e}}))})).map((function(e){var t=e.Cobra,n=e.channel;return new t.SourceInitializer(n,$g()).initialize()})).publishReplay().refCount(),this.stopSourceObservable=this.sourceObservable.switchMap((function(e){return i.take(1).map((function(){return e}))})).catch((function(){return Gv.Observable.empty()})),this.hideMouseObservable=c.switchMap((function(e){return o.takeUntil(i).map((function(){return e}))})).catch((function(){return Gv.Observable.empty()}))}var ET,OT,ST=function(){function e(t,n,r,i){s(this,e),this._sendActivityFromCobrowsableIframe=this._sendActivityFromCobrowsableIframe.bind(this),this.windowMessenger=t,this.channelUrl=n,this.getAccessToken=r,this.stats=i}return c(e,[{key:"boot",value:function(){this._activityObservable().subscribe(this._sendActivityFromCobrowsableIframe);var e=new wT({getAccessToken:this.getAccessToken,stats:this.stats,start:this._startObservable(),stop:this._stopObservable(),hideMouse:this._hideMouseObservable()});e.sourceObservable.subscribe((function(){return nm.log("Source started for cobrowsable iframe")}),(function(e){return nm.error("Couldn't start visitor cobrowsable iframe ".concat(e))})),e.stopSourceObservable.subscribe((function(e){return e.stop()}),nm.error.bind(nm,"cobra stop subscription error")),e.hideMouseObservable.subscribe((function(e){return e.toTag("cobrowse").emit("cobra:hide_mouse")}),nm.error.bind(nm,"cobra hide mouse subscription error")),nm.info("Started for visitor Nested CoBrowsable iFrame")}},{key:"_startObservable",value:function(){var e=this.channelUrl?Gv.Observable.of(this.channelUrl):Gv.Observable.empty();return this._cobrowsableFrameInviteObservable(this.windowMessenger).share().merge(e)}},{key:"_stopObservable",value:function(){return this.windowMessenger.observable("cobra:cobrowsable_iframe:stop")}},{key:"_hideMouseObservable",value:function(){return this.windowMessenger.observable("cobra:hide_mouse")}},{key:"_activityObservable",value:function(){return sm.PeriodicalActivityTracker.getStream(_T)}},{key:"_cobrowsableFrameInviteObservable",value:function(e){return Gv.Observable.create((function(t){return e.respondTo("cobra:cobrowsable_iframe:join_channel_and_cobrowse",(function(e,n){var r=e.url;return n(),t.next(r)}))}))}},{key:"_sendActivityFromCobrowsableIframe",value:function(){return this.windowMessenger.emit("activity_from_cobrowsable_iframe")}}]),e}(),TT=new Error("Tried to connect internal visitor state subscription after already connected"),kT=null,xT=k.compose(k.map(k.pick(["id","site_id","operator_id"])),k.pathOr([],["engagement","observations"])),AT=k.compose(k.map(k.pick(["id","site_id","operator_id","outcome"])),k.pathOr([],["engagement","requests"])),IT=k.compose(k.map(k.pick(["id","site_id","status","sub_engagement_id"])),k.pathOr([],["engagement","engagements"])),NT=k.compose(k.map(k.pick(["id","site_id","state"])),k.pathOr([],["omniq","queue_tickets"])),CT=function(e,t){return k.pathOr({},["routing","".concat(sm.siteId),"".concat(t)],e)},RT=function(e){var t=e.pubsub,n=e.tabId,r=e.allowConnectingMultipleTimes,o=e.visitorIdObservable,s=void 0===o?Yv():o;return kT&&!r?nm.error(TT):((kT=s.switchMap((function(e){return t.joinChannel("visitor_state:".concat(e)).flatMap((function(e){return(0,e.observable)("change",{leaveChannelOnDispose:!0})})).map((function(t){return i(i({},t||{}),{},{visitor_id:e})}))})).do((function(e){return function(e,t){return nm.info("Received internal visitor state",{routing:CT(e,t),observations:xT(e),engagement_requests:AT(e),engagements:IT(e),queue_tickets:NT(e)})}(e,n)})).publishReplay(1)).connect(),kT)},PT=sm.logger,MT=function(e){var t=e.status,n=e.body,r=e.error;if(t>=200&&t<300)return Gv.Observable.of(n);var i=k.find(k.compose(k.not,k.isNil),[r,n,"unknown"]);return k.is(String,i)?Gv.Observable.throw({status:t,reason:i}):Gv.Observable.throw(k.merge({status:t},i))},jT=function(e){return k.is(Object,e)&&"timeout"===e.type?Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT})):Gv.Observable.throw(e)},LT=k.propEq("persisted",!0);k.has("onpagehide",window)?(ET=Gv.Observable.fromEvent(window,"pageshow").share(),OT=Gv.Observable.fromEvent(window,"pagehide").share()):(ET=Gv.Observable.fromEvent(window,"load").share(),OT=Gv.Observable.fromEvent(window,"unload").share());var qT={unloadMaybeToPageCache:OT,loadFromPageCache:ET.filter(LT)},UT=new RegExp("sm."),DT=function(e){return"sm.".concat(e)},VT={set:function(e,t){sessionStorage.setItem(DT(e),function(e){return JSON.stringify(e)}(t))},get:function(e){return function(e){try{return JSON.parse(e)}catch(e){return null}}(sessionStorage.getItem(DT(e)))},remove:function(e){sessionStorage.removeItem(DT(e))},removeAll:function(){for(var e=0;e0||QT(e).length>0||YT(e).length>0}(e)?WT:GT},XT=function(e,t){var n=e.indexOf(t);return n>-1?[e.substring(0,n),e.substring(n+1)]:[e]},$T=function(e,t,n){n||(n="");var r=g(XT(e,"#"),2),i=r[0],o=r[1],s=g(XT(i,"?"),2),a=s[0],c=s[1],u=k.compose(k.join("&"),k.map(k.concat(n)),k.map(k.join("=")),k.map(k.map(encodeURIComponent)),k.toPairs)(t),l=c?"".concat(a,"?").concat(c,"&").concat(u):"".concat(a,"?").concat(u);return o?"".concat(l,"#").concat(o):l},ZT=function(){if("function"!=typeof window.getGliaContext)return Promise.resolve({sessionId:null,idToken:null});try{var e=window.getGliaContext();"function"!=typeof e.then&&(e=Promise.resolve(e));return e.then((function(e){return Promise.resolve(i(i({},{sessionId:null,idToken:null}),e))}),(function(e){return nm.error("getGliaContext() promise rejected",{error:e}),Promise.resolve({sessionId:null,idToken:null})})).catch((function(e){return nm.error("Unexpected error in getGliaContext() promise",{error:e}),Promise.resolve({sessionId:null,idToken:null})}))}catch(e){return nm.error("Unexpected error in getGliaContext()",{error:e}),Promise.resolve({sessionId:null,idToken:null})}},ek=function(){return Gv.Observable.create((function(e){ZT().then((function(t){e.next(t),e.complete()}))}))},tk=function(e){try{var t=function(e){var t=e.split(".")[1],n=decodeURIComponent(atob(t).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""));return JSON.parse(n)}(e);return(t.exp-t.iat)/2*1e3}catch(e){return nm.warn("Fetching interval from access token failed",e),864e5}},nk=function(e){return e&&"string"==typeof e},rk=function(e){var t=e.priority,n=e.accessToken,r=e.consolidationSecret,i=e.url,o=e.tabId,s=e.detectVisitorByExternalSessionTokenEnabled,a=e.opaqueVisitorAuthenticationEnabled;return i||(i=sm.visitorConfigUrl),i=$T(i,{priority:t,tab_id:o}),Gv.Observable.create((function(e){var t=new XMLHttpRequest;return t.onreadystatechange=function(){if(4===this.readyState)if(200===this.status){var n=JSON.parse(t.responseText);e.next({accessToken:n.access_token,visitorId:n.visitor_id,authenticatedExternally:Boolean(n.authenticated_externally)}),e.complete()}else e.error({responseText:t.responseText,status:t.status})},function(e){var t=e.detectVisitorByExternalSessionTokenEnabled,n=e.opaqueVisitorAuthenticationEnabled;return ZT().then((function(e){var r=e.sessionId,i=e.idToken;return[t&&nk(r)?"external_session_id=".concat(r):"",n&&nk(i)?"id_token=".concat(i):""]}))}({detectVisitorByExternalSessionTokenEnabled:s,opaqueVisitorAuthenticationEnabled:a}).then((function(e){var o=g(e,2),s=o[0],a=o[1],c=[r?"consolidation_token=".concat(encodeURIComponent(r)):null,n?"access_token=".concat(encodeURIComponent(n)):null,s,a].filter(k.identity).join("&");t.open("POST",i,!0),t.withCredentials=!0,t.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),t.send(c)})),function(){return t.abort()}}))},ik=function(){function e(t){s(this,e),this.attributes=k.clone(t),this.id=this.attributes.id}return c(e,[{key:"get",value:function(e){return this.attributes[e]}},{key:"set",value:function(e){var t=this;Object.keys(e).forEach((function(n){var r=e[n];t.attributes[n]=r}))}},{key:"getId",value:function(){return this.get("id")}},{key:"getName",value:function(){return this.get("name")}},{key:"getFormattedName",value:function(){return this.get("formattedName")}},{key:"getMediaType",value:function(){return this.get("media_type")}},{key:"isOnline",value:function(){return!this.isUnavailable()}},{key:"currentlyAvailable",value:function(){return!this.currentlyUnavailable()}},{key:"currentlyUnavailable",value:function(){return this.isEngaged()||this.isUnavailable()}},{key:"isEngaged",value:function(){return"engaged"===this.get("status")}},{key:"mediaRank",value:function(){switch(this.getMediaType()){case"text":return.8;case"audio":return.9;case"video":return 1;default:return 0}}},{key:"getPictureUrl",value:function(){var e=this.get("picture")&&this.get("picture").url,t=sm.conf.visitor_app.always_use_default_operator_picture,n=sm.conf.visitor_app.default_operator_picture.url;if(!n||!t&&e){var r=-1!==sm.conf.assets.server.indexOf("libs.")?"/":sm.conf.assets.prepend;return e||[sm.conf.assets.server,r||"/","default_operator_picture-ea662fcc3.png"].join("")}return n}},{key:"isUnavailable",value:function(){return!1===this.get("available")}}]),e}(),ok=function(e){return k.filter(k.contains(k.__,["video"]),e)};function sk(e){return/iPad|iPhone|iPod/.test(e)&&!window.MSStream}function ak(e){return/^((?!CriOS|Chrome|Android).)+Safari/.test(e)}function ck(e){return 0===e.length}function uk(e,t){return-1!==t.indexOf(e)}function lk(e){var t=e.match(/OS ((\d+_?){2,3})\s/);if(!t)return!1;var n=t[1].split("_"),r=n[0]+"."+n[1];return parseFloat(r)>=11.3}function pk(e){if(sk(e))return lk(e);var t=function(e){var t=e.match(/Version\/([0-9]+\.[0-9]*)/);return t&&parseFloat(t[1],10)}(e);return!!t&&t>=11}function fk(){return[{name:"RTCPeerConnection",pass:Boolean(window.RTCPeerConnection)},{name:"RTCIceCandidate",pass:Boolean(window.RTCIceCandidate)},{name:"AudioContext",pass:Boolean(window.AudioContext)||Boolean(window.webkitAudioContext)},{name:"MediaStream",pass:Boolean(window.MediaStream)}]}function hk(){return[].concat(_(fk()),[{name:"getUserMedia",pass:Boolean(window.navigator.mediaDevices)&&Boolean(window.navigator.mediaDevices.getUserMedia)}])}var dk={video:"camera",audio:"microphone"};function bk(e,t,n){if(null==n)return!0;var r=dk[t];return!!uk(r,n)&&(!ak(e)||!uk("".concat(r," *"),n))}function vk(){var e=window.navigator.userAgent;return!(ak(e)&&sk(e)&&!lk(e))&&ck(fk().filter((function(e){return!e.pass})))}function mk(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.media,n=e.iframeAllow,r=window.navigator.userAgent;if(!bk(r,t,n))return!1;if(ak(r)&&!pk(r))return!1;var i=hk().filter((function(e){return!e.pass}));return ck(i)}var yk=Object.freeze({__proto__:null,canReceiveMedia:vk,canSendMedia:mk}),gk="none",_k="receiver",wk="duplex",Ek=function(){return vk()?mk()?wk:_k:gk},Ok=["video","audio"],Sk={video:["video","audio","phone","text"],audio:["audio","phone","text"],phone:["phone","text"],text:["text"]},Tk=k.lensPath(["state","medias"]),kk=k.lensPath(["state","oneWayMedias"]),xk=function(e,t){var n=k.difference(e.state[t],Ok);return k.assocPath(["state",t],n,e)},Ak=k.curry((function(e,t){return e===wk||e===_k?t:xk(t,"oneWayMedias")})),Ik=k.curry((function(e,t){return e===wk?t:xk(t,"medias")})),Nk=function(e){return k.assocPath(["state","media"],e.state.medias,e)},Ck=k.curry((function(e,t){var n,r=e.enabledMediaType,i=e.webRtcMode;return k.compose(Nk,Ak(i),Ik(i),(n=r,k.over(kk,k.intersection(ok(Sk[n])))),function(e){return k.over(Tk,k.intersection(Sk[e]))}(r))(t)})),Rk=function e(t){var n=t.id,r=t.name,i=t.formattedName,o=t.picture,a=t.state;s(this,e),this.id=n,this.name=r,this.formattedName=i||(null==r?void 0:r.split(" ")[0]),this.picture=o,this.state=a,this.assignment={type:"direct"}},Pk=function(e){l(n,e);var t=m(n);function n(){return s(this,n),t.apply(this,arguments)}return c(n,[{key:"serialize",value:function(){return new Rk({id:this.getId(),name:this.getName(),formattedName:this.getFormattedName(),picture:this._getPicture(),state:this._getState()})}},{key:"_getPicture",value:function(){return{url:this.getPictureUrl()}}},{key:"_getState",value:function(){var e=Sk[this.getMediaType()];return{available:this.currentlyAvailable(),medias:e,oneWayMedias:ok(e)}}}]),n}(ik),Mk=k.curry((function(e,t){var n=e.enabledMediaType,r=e.webRtcMode,i=new Pk(t.attributes).serialize();return Ck({enabledMediaType:n,webRtcMode:r},i)})),jk=function(e){var t=e.id,n=e.name,r=e.formattedName,i=e.picture,o=e.mediaType,s=e.webRtcMode,a=e.enabledMediaType,c=new Pk({id:t,name:n,formattedName:r,picture:i,media_type:o});return Mk({enabledMediaType:a,webRtcMode:s},c)},Lk=function(e){var t=e.enabledMediaLevel,n=e.webRtcMode,r=function(e,t){return{operator:e,isVisible:void 0!==e.state.available&&e.reactiveEnabled&&(k.isEmpty(t)||!k.isEmpty(k.intersection(e.teamIds,t)))}};return{fromPresence:function(e,i,o){var s=i.state,a=k.pathOr("operator",["operator_information","name"],s),c=k.pathOr(null,["operator_information","picture","url"],s),u=k.pathOr([],["operator_information","teams"],s),l=k.map(k.prop("id"),u),p=k.pathOr(!0,["operator_information","reactive_enabled"],s),f=k.pathOr([],["engagement","media"],s),h=k.has("engagement",s);-1!==f.indexOf("audio")&&f.push("phone");var d={id:e,name:a,picture:{url:c},state:{available:h?!k.isEmpty(f):void 0,media:f,medias:f,oneWayMedias:f},teamIds:l,reactiveEnabled:p};return d=Ck({enabledMediaType:t,webRtcMode:n},d),r(d,o)},updateVisibility:r}},qk=function e(t,n){t||(t={}),n||(n={});return{omit:function(r){return e(k.dissoc(r,t),k.dissoc(r,n))},set:function(r){var i=r.operator,o=r.isVisible?k.assoc(i.id,i,n):k.dissoc(i.id,n);return e(k.assoc(i.id,i,t),o)},forEach:function(e){return k.values(t).forEach(e)},immutableFacade:function(){return{get:function(e){var t=n[e];return t?new Rk(t):t},values:function(){return k.map(k.construct(Rk),k.values(n))}}}}},Uk=function(e){var t=e.presence,n=e.presenceMapper,r=e.visibleTeamsObservable,i=e.onChange,o=qk(),s=[],a=r.subscribe((function(e){s=e,o.forEach((function(e){var t=n.updateVisibility(e,s),r=t.operator,i=t.isVisible;o=o.set({operator:r,isVisible:i})})),i(o.immutableFacade())}));t.list((function(e,t){return n.fromPresence(e,t,s)})).forEach((function(e){var t=e.operator,n=e.isVisible;o=o.set({operator:t,isVisible:n})})),i(o.immutableFacade()),t.onChange((function(e,t,r){if(r.metas.length>0){var a=n.fromPresence(e,r,s),c=a.operator,u=a.isVisible;o=o.set({operator:c,isVisible:u})}else o=o.omit(e);i(o.immutableFacade())}));return{stop:function(){return a.unsubscribe()}}},Dk="salemove",Vk=function(e){try{return JSON.parse(e.name)||{}}catch(e){return{}}},Fk=function(e){return""===e.name},Bk=function(e){return Fk(e)||function(e){return Vk(e).hasOwnProperty(Dk)}(e)},Hk=function(e){return k.lensPath([Dk,e])},Wk=[void 0,null,"javascript:;",""],Gk=!1,zk=function(e,t){if(t||(t=sm.conf.navigatable_hostnames),k.contains(e,Wk))return!0;var n=Gk?t.engaged:t.available;return k.any((function(t){return e.indexOf(t)>-1}))(n)},Jk={isInEngagement:Gk,setEngagedStatus:function(e){Gk=e},extractLinkFromEvent:function(e){try{var t=e.target;return t&&(t=function(e,t){t=t.toUpperCase();do{if(e.nodeName===t)return e}while(e=e.parentNode);return null}(t,"a")),t}catch(e){return null}},isAllowedToNavigate:zk},Qk=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.isAllowed,n=void 0===t?zk:t;Hm(document.querySelectorAll('a[target="_blank"]')).filter((function(e){return"javascript:void(0)"!==e.href})).filter((function(e){return n(e.hostname)})).forEach((function(e){return e.setAttribute("target","_self")}))},Yk=["target","defaultPrevented","ctrlKey","shiftKey","metaKey","button"],Kk=function(e){var t=e.getCurrentUrl,n=e.linkHandler,r=e.clicks,i=e.navigate,o={},s=function(e){var t=e.event,n=e.link;try{var r=n.href;sm.logger.info("XDomainUrlStorage: adding params to URL",{params:o});var s=$T(r,o,"__sm.");sm.logger.info("XDomainUrlStorage: navigating to modified URL",{original_url:r,modified_url:s}),t.preventDefault(),i(s)}catch(e){sm.logger.error("XDomainUrlStorage: error trying to store values in URL",e)}},a=function(e){return"_blank"!==e.link.target},c=function(e){var t=e.link;return!k.isEmpty(t.href)&&!k.isNil(t.href)&&k.contains(t.protocol,["http:","https:"])},u=function(e){var n=e.link;return!k.contains(n.hostname,t())},l=function(e){var t=e.link;return n.isAllowedToNavigate(t.hostname)},p=function(e){var t=e.event;return!(t.ctrlKey||t.shiftKey||t.metaKey)},f=function(e){return 0===e.event.button},h=function(e){try{return Yk.forEach((function(t){return e[t]})),!0}catch(e){return!1}},d=function(e){return!e.defaultPrevented},b=function(e){for(var t=e.target;t&&t.nodeName&&"a"!==t.nodeName.toLowerCase();)t=t.parentElement;return t};return{start:function(){return r.filter((function(){return!k.isEmpty(o)})).filter(h).filter(d).map((function(e){return{event:e,link:b(e)}})).filter(k.where({link:k.complement(k.isNil)})).filter(c).filter(a).filter(u).filter(p).filter(f).filter(l).subscribe(s,(function(e){return sm.logger.error("XDomainUrlStorage: error while filtering user click event",e)}),(function(){return sm.logger.error("XDomainUrlStorage: clicks observable was completed")}))},setItem:function(e,t){o=k.assoc(e,t,o)},getItem:function(e){return sm.urlParams?sm.urlParams[e]:void 0}}},Xk="sm.",$k=function(){return{getItem:function(e){return window.localStorage.getItem(Xk+e)},setItem:function(e,t){return window.localStorage.setItem(Xk+e,t)},removeItem:function(e){return window.localStorage.removeItem(Xk+e)}}},Zk=function(){var e,t,n=(e=window,{getItem:function(t){if(!Fk(e))return k.view(Hk(t),Vk(e))},setItem:function(t,n){if(Bk(e)){var r=Vk(e),i=k.set(Hk(t),n,r);e.name=JSON.stringify(i)}}}),r=(t=Gv.Observable.merge(Xm(document,"click"),Xm(document,"mousedown")),new Kk({getCurrentUrl:function(){return window.location.href},linkHandler:Jk,clicks:t,navigate:function(e){window.location.href=e}}));sm.conf.visitor_api&&sm.conf.visitor_api.persist_visitor_session_in_url&&r.start();var i,o=new $k;return{bestEffortXDomainStorage:(i={prioritizedStorages:[n,r,o]}.prioritizedStorages,{getItem:function(e){return function(e,t){for(var n=0;n0?{queue_ids:t.map((function(e){return e.id}))}:{}}(e,n)})).distinctUntilChanged(k.equals)},tx="sm.app.visitor_api.custom_code",nx=function(e){var t=e.stats,n=e.loadCustomCodeScript,r=sm.conf.customCodeFile?sm.conf.customCodeFile.url:void 0;return r?(n||(n=P),new Promise((function(e,i){var o={integrity:C()?sm.conf.customCodeFile.sri:null,fileUrl:r,beforeLoad:function(){return e({ignored:!1})},onAttempt:function(){return t.increment(tx,["action:attempted"])},onLoad:function(){return t.increment(tx,["action:succeeded"])},onError:function(){return t.increment(tx,["action:warning"])},onGiveUp:function(){return t.increment(tx,["action:failed"]),sm.logger.warn(new Error("Failed to load custom code"),{custom_code_url:r})}};return n(o)}))):Promise.resolve({ignored:!0})};function rx(e,t){var n=t.targetWindow,r=t.logger,i="__sm.",o=n.location.search,s=n.location.href;try{var a=o.replace("?","").split("&").filter((function(e){return e.indexOf(i)>-1})),c=a.map((function(e){return e.split("=")})).map((function(e){var t=g(e,2),n=t[0],r=t[1];return{key:n.replace(i,""),value:r}})).map((function(e){var t=e.key,n=e.value;return{key:decodeURIComponent(t),value:decodeURIComponent(n)}})).reduce((function(e,t){var n=t.key,r=t.value;return e[n]=r,e}),{}),u=a.reduce((function(e,t){return e.replace("?".concat(t),"").replace("&".concat(t),"")}),s);return u!==s&&(r.info("Found sm params in URL",{params:c,url_length:s.length}),(n.history?n.history.replaceState:void 0)&&(r.info("Replacing page URL",{original_url:s,new_url:u}),n.history.replaceState(n.history.state,n.document.title,u))),function(t){return Object.keys(e).filter((function(e){return Boolean(t[e])})).map((function(n){return{key:n,value:t[n],regex:e[n]}})).reduce((function(e,t){var n=t.key,i=t.value,o=t.regex;return i.match(o)?e[n]=i:r.error("URL query param does no satisfy provided regex",{param_key:n,param_value:i,regex:o}),e}),{})}(c)}catch(e){return r.error("Error reading sm params from URL",e),{}}}function ix(e,t){var n,r=t.salemovePresentInParent,i=function(){var t={url:e.location.href,page_title:e.title};if(r)return window.parent.postMessage(JSON.stringify({"sm-xdr-url":t.url}),"*")};this.start=function(){n=new Gv.Subscription;var e=sm.hrefObservable.skip(1);return n.add(e.subscribe(i,nm.error))},this.stop=function(){n&&n.unsubscribe()}}var ox=function(e){return k.reduce(k.maxBy(k.prop("activity_at")),e[0],e)},sx=function(e,t){return t?!e||e.activity_at0||l(e).length>0||p(e).length>0||f(e).length>0};i.filter(h).take(1).subscribe((function(){return t.requestStart()})),i.take(1).filter(k.complement(h)).subscribe((function(){return t.requestStartWhenSpaceAvailable()}))}else t.requestStart();var d,b=(d={internalVisitorStateObservable:i},d.internalVisitorStateObservable.map(vx).distinctUntilChanged(k.equals).startWith({}).bufferCount(2,1).do(mx).map((function(e){var t=g(e,2);return t[0],t[1]})).startWith({})).publishReplay(1);b.subscribe((function(e){Jk.setEngagedStatus("engagement"===e.interaction)}));var v=function(e,t,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Yv();return e.distinctUntilChanged(null,(function(e){return e.channelUrl})).switchMap((function(e){return i.pipe(ub((function(){return e})))})).do(null,nm.warn.bind(nm,"Failed to setup channel observable")).filter((function(e){return Boolean(e.interaction)})).switchMap((function(e){return t.getUserIsActiveTabObservable().take(1).map((function(t){return{status:e,isActiveTab:t}}))})).switchMap((function(e){var t=e.status,i=e.isActiveTab;return gT({channelUrl:t.channelUrl,participantId:"visitor",operatorId:t.operator.id,isActiveTab:i,getAccessToken:n,stats:r}).catch((function(){return Gv.Observable.empty()})).map((function(e){return{channel:e,operator:t.operator}}))})).share()}(b,t,o,s).publishReplay(1);return sm.channelSubscription=v.connect(),b.connect(),{statusObservable:b,channelObservable:v.filter((function(e){var t=e.channel,n=e.operator;return!t.isStopped()||(nm.warn("Filtering out stopped channel in channelObservable",{channelUrl:t.url,operator:n,siteId:sm.siteId}),!1)})),tracker:t}},gx={get:function(e){return e.checked},set:function(e,t){e.checked=t}},_x={select:{get:function(e){return k.compose(k.fromPairs,k.map((function(e){return[e.index,e.selected]})))(e.options)},set:function(e,t){k.forEach((function(e){e.selected=t[e.index]}))(e.options)}},option:{get:function(e){return e.selected},set:function(e,t){e.selected=t}},radio:gx,checkbox:gx,default:{get:function(e){return e.value},set:function(e,t){if("function"==typeof Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(e,"value")&&Object.getOwnPropertyDescriptor(e,"value").set)try{return Object.getOwnPropertyDescriptor(e.constructor.prototype,"value").set.call(e,t)}catch(n){e.value=t}else e.value=t}}},wx=function(e){var t=_x[e.type]||_x[e.nodeName&&e.nodeName.toLowerCase()]||_x.default,n=t.get,r=t.set;return{get:function(){return n(e)},set:function(t){r(e,t)}}},Ex="sm_engagement_serialized_inputs",Ox=function(e,t){return k.compose(k.forEach((function(t){var n=t.destInput,r=t.value;return t.hook.set(r),function(e,t){var n=e.createEvent("HTMLEvents");return n.initEvent("change",!0,!1),t.dispatchEvent(n)}(e,n)})),k.filter((function(e){var t=e.hook,n=e.value;return!k.equals(t.get(),n)})),k.map((function(e){var t=e.destInput;return{destInput:t,value:e.value,hook:wx(t)}})),k.filter((function(e){var t=e.destInput;return Boolean(t)})),k.map((function(t){var n=t.value,r=t.xpath;return{value:n,destInput:Km(e,r)}})))(t)},Sx=function(e){var t=k.compose((function(e){return Array.prototype.slice.call(e)}),(function(t){return e.getElementsByTagName(t)})),n=k.chain(t,["INPUT","TEXTAREA","SELECT","PASSWORD","CHECKBOX","RADIO"]);return k.map((function(e){return{value:wx(e).get(),xpath:Jm(e)}}),n)},Tx=[k.ifElse(k.path(["state","available"]),k.always(1),k.always(0)),k.compose(k.length,k.path(["state","media"]))],kx=k.reduce(k.maxBy((function(e){return k.ap(Tx,[e])})),null),xx=function(e){return sm.conf.api_url+e},Ax=function(e){return function(e){return e.filter(k.propEq("connected",!1))}(e).switchMap((function(){return e.filter(k.propEq("connected",!0)).take(1)}))},Ix=function(e,t,n){t||(t=qg);var r=(n&&void 0!==n.authenticatedExternally?n.authenticatedExternally:sm.authenticatedExternally)?"/messaging/chat_transcript?_=".concat(Date.now()):"/engagements/".concat(e,"/chat_transcript?_=").concat(Date.now());return t({url:xx(r)}).pipe(ub(k.prop("response")),Bb(),Rd((function(t){return nm.warn("Failed to fetch chat history",{error:t,engagement_id:e}),vt([])})))},Nx=function(e){var t=e.engagementId,n=e.connectionStatusObservable,r=e.requestAsObservable;return Ax(n).pipe(vb((function(){return Ix(t,r)})),Fb())},Cx=Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR})).do(null,(function(){return nm.warn("Operators observable timed out!")})),Rx=function(e,t){t||(t=[]);return e.increment("engagement.flow",["entrypoint:reactive-request"].concat(t))},Px=function(e,t,n,r){r||(r=Gv.Scheduler.asap);var i=t||{},o=i.operatorId,s=i.phoneNumber,a=i.phoneExtension,c=i.source,u=i.oneWay,l=i.siteId;l||(l=sm.siteId);var p=n.api,f=n.operatorsObservable,h=n.serverResponseTimeout,d=n.engagementCoreObservable,b=n.mediaValidation,v=n.statsClient;nm.info("Engagement: Reactive request initiated",{media:e,options:t});var m=o?k.find(k.propEq("id",o)):kx,y=f.timeoutWith(h,Cx,r).map(m).flatMap((function(e){return e?Gv.Observable.of(e):Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.OPERATOR_UNAVAILABLE}))}));return Gv.Observable.combineLatest(y,d).flatMap((function(n){return function(n){var i=n.state.medias,o=n.state.oneWayMedias;return Gv.Observable.fromPromise(b({media:e,options:t,availableMediaTypes:i,availableOneWayMediaTypes:o}),r).map(k.always(n))}(g(n,1)[0])})).flatMap((function(t){var n={phoneNumber:s,phoneExtension:a,oneWay:u};return Rx(v,["action:reach","stage:create-request"]),p.create({operatorId:t.id,siteId:l,media:e,source:c,mediaOptions:n}).map((function(r){return k.merge(r,{operator:t,media:e,mediaOptions:n})}))}))},Mx=function(e,t){t||(t=Gv.Scheduler.asap);var n=e.media,r=e.mediaOptions,i=e.mediaValidation,o=e.api,s=e.notifyOfTimeout,a=e.operatorsObservable,c=e.engagementCoreObservable,u=e.cobraObservable,l=e.channelObservable,p=e.serverResponseTimeout,f=e.communicationLib,h=e.engagementApi,d=e.webRtcMode,b=e.enabledMediaLevel,v=e.statsClient,m=Px(n,r,{api:o,operatorsObservable:a,serverResponseTimeout:p,engagementCoreObservable:c,mediaValidation:i,statsClient:v},t).publishReplay(),y=m.connect();Rx(v,["action:begin"]);var g=m.flatMap((function(e){var n=e.engagementRequestId,r=e.acknowledgeTimeoutSeconds,i=e.operator;return Rx(v,["action:reach","stage:requested"]),Gv.Observable.combineLatest(o.acceptedObservable,u,l,(function(e,t){return k.merge(e,{cobra:t})})).timeoutWith(1e3*r+p,function(e,t){return Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT})).do(null,(function(){return nm.warn("Engagement request timed out! Some internal listener must be missing.")})).do(null,(function(){return e.notifyOfReactiveFailure({id:t})}))}(o,n),t).merge(ty(function(e){return Gv.Observable.merge(o.declinedObservable.map(k.always(new ag({cause:Ky.SALEMOVE.OPERATOR_DECLINED}))),o.timedOutObservable.do((function(){return s({operator:e})})).map(k.always(new ag({cause:Ky.SALEMOVE.TIMEOUT}))))}(i))).take(1)})).do(null,k.ifElse(k.propEq("cause",Ky.SALEMOVE.INTERNAL_ERROR),nm.warn.bind(nm,"Engagement: Reactive request failed"),nm.info.bind(nm,"Engagement: Reactive request failed"))).do(null,(function(e){return Rx(v,["action:end"].concat(function(e){return e&&e.cause===Ky.SALEMOVE.OPERATOR_UNAVAILABLE?["stage:pre-request","expected:true","reason:target-unavailable"]:e&&e.cause===Ky.SALEMOVE.INVALID_INPUT?["stage:pre-request","reason:invalid-input"]:e&&e.cause===Ky.SALEMOVE.INTERNAL_ERROR?["stage:create-request","reason:internal-error"]:e&&e.cause===Ky.SALEMOVE.TIMEOUT?["stage:requested","expected:true","reason:accept-timeout"]:e&&e.cause===Ky.SALEMOVE.OPERATOR_DECLINED?["stage:requested","expected:true","reason:decline"]:e&&e.cause===Ky.SALEMOVE.NETWORK_TIMEOUT?["stage:create-request","reason:network-error"]:["stage:pre-request","reason:script-load-error"]}(e)))})).map((function(e){var t,r,i,o,s,a,c,u,p,v;i=e.engagementId,v=e.subEngagementId,t=e.cobra,n=e.media,s=e.operatorId,c=e.operatorName,u=e.operatorFormattedName,p=e.operatorPicture,a=e.operatorMediaType,o=e.entrypoint,r=e.createdAt;var m=jk({id:s,name:c,formattedName:u,picture:p,mediaType:a,webRtcMode:d,enabledMediaType:b});return nm.info("Engagement: Reactive request accepted",{engagementId:i,subEngagementId:v,operator:m}),{engagementId:i,subEngagementId:v,startingMedia:n,type:"reactive",isReestablishing:!1,initialChatHistoryObservable:Ix(i),operator:m,communicationLib:f,cobra:t,channelObservable:l,engagementApi:h,entrypoint:o,createdAt:r}})).take(1).finally((function(){return y.unsubscribe()}));return{requestObservable:m,resultObservable:g}},jx=function e(t){var n=t.id,r=t.content,i=t.status,o=t.attachment,a=t.created_at;if(s(this,e),this.id=n,this.content=r,this.sender="visitor",this.sender_details={type:"visitor"},this.status=null,this.attachment=o,this.created_at=a,i){if(!k.find(k.equals(i),k.values(this.STATUSES)))throw new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR,message:"Unknown status ".concat(i)});this.status=i}};jx.prototype.STATUSES={SENDING:"sending",DELIVERED:"delivered",FAILED:"failed"},jx.prototype.ATTACHMENT_RESPONSE_TYPES={SINGLE_CHOICE_RESPONSE:"single_choice_response",FILES:"files"};var Lx=function e(t){var n=t.id,r=t.content,i=t.attachment,o=t.metadata,a=t.created_at,c=t.sender,u=void 0===c?{}:c;s(this,e),this.id=n,this.content=r,this.sender="operator",this.sender_details={type:"operator",name:u.name,picture:u.picture?u.picture.url:"",id:u.id},this.attachment=i,this.metadata=o,this.created_at=a};Lx.prototype.ATTACHMENT_TYPES={SINGLE_CHOICE:"single_choice",FILES:"files"};var qx=function e(t){var n=t.id,r=t.content,i=t.attachment,o=t.metadata,a=t.created_at;s(this,e),this.id=n,this.content=r,this.sender="system",this.sender_details={type:"system"},this.attachment=i,this.metadata=o,this.created_at=a};qx.prototype.ATTACHMENT_TYPES={SINGLE_CHOICE:"single_choice",FILES:"files"};var Ux=sm.conf.visitor_app_option,Dx=function(e,t){return e===t},Vx={VISITOR:"visitor",OPERATOR:"operator",SYSTEM:"system"},Fx=function(e,t){var n=k.differenceWith(k.eqProps("id"),e,t);return 0===n.length?t:k.concat(n,t)},Bx=function(e,t,n){var r=e.pipe(hb(t),Db((function(e,t){var n=k.findIndex(k.propEq("id",t.id),e);return-1!==n?k.update(n,t,e):k.prepend(t,e)}),[]),Qb([]));return dt(r,n,Fx).pipe(Jd(Dx))},Hx=function(e){var t=e.id,n=e.sender,r=e.message,i=e.attachment,o=e.metadata,s=n.type;return s===Vx.VISITOR?new jx({id:t,content:r,attachment:i,status:jx.prototype.STATUSES.DELIVERED}):s===Vx.OPERATOR?new Lx({id:t,content:r,attachment:i,metadata:o,sender:n}):s===Vx.SYSTEM?new qx({id:t,content:r,attachment:i,metadata:o}):void 0},Wx=function(e){return k.map(Hx,e).reverse()},Gx=function(e){var t=e.chatHistoryObservable,n=e.ownMessages,r=e.operatorMessages,i=e.statsClient,o=e.fetchExtraOperatorInfo,s=n.pipe(ub((function(e){var t=e.id,n=e.content,r=e.attachment;return new jx({id:t,content:n,attachment:r,status:null})}))),a=n.pipe(vb((function(e){var t=e.id,n=e.content,r=e.status,i=e.attachment;return r.pipe(ub((function(e){return new jx({id:t,content:n,attachment:i,status:e})})))})));r=r.pipe(zd(k.prop("id")),vb((function(e){var t=e.sender.id;return o(t).pipe(ub((function(t){return k.evolve({sender:k.merge(t)})(e)})))})),ub((function(e){var t=e.id,n=e.content,r=e.attachment,i=e.metadata,o=e.sender;return new Lx({id:t,content:n,attachment:r,metadata:i,sender:o})})));var c=t.map(Wx),u=Bx(a,r,c).pipe(nv((function(){i.increment("sm.app.visitor_api.chat.messages",["action:emitted","visitor_app:".concat(Ux)])})));return{messages:Bx(s,r,c),messagesWithStatusUpdates:u}},zx=function e(t){var n=t.typing;s(this,e),this.typing=n},Jx="visitor";function Qx(e){this.recordChatMessageSent=function(t){1===t?e.increment("sm.".concat(Jx,".communication.chat.message.sent")):e.increment("sm.".concat(Jx,".communication.chat.message.retry"))},this.recordChatMessageDeliveryFailed=function(){e.increment("sm.".concat(Jx,".communication.chat.message.delivery_failed"))},this.recordChatMessageDelivered=function(){e.increment("sm.".concat(Jx,".communication.chat.message.delivered"))}}var Yx={SENDING:"sending",DELIVERED:"delivered",FAILED:"failed"},Kx="Chat",Xx=function(){function e(t){var n=t.chatApi,r=t.messagesToSend,i=t.previewToSend,o=t.deliveryTimeout,a=void 0===o?sm.conf.chat_message_send_timeout_ms||15e3:o,c=t.history,u=t.guid,l=void 0===u?Ey:u,p=t.stats,f=t.logger;s(this,e),this._chatApi=n,this._previewToSend=i,this._history=c,this._generateGuid=l,this._messagesToSend=r,this._deliveryTimeout=a,this.stats=p,this.logger=f,this._messengerStoppedSubject=new Re,this._sentMessages=new Re,this._deliveryEvents=this._chatEvents("deliveredMessages"),this._receivedMessageIds=[],this._subscription=new se}return c(e,[{key:"start",value:function(){var e=this;this._subscription.add(this._messagesToSend.subscribe(this._sendMessage.bind(this),this.logger.error)),this._subscription.add(this._previewToSend.subscribe((function(t){return e._chatApi.sendPreview({content:t})}),this.logger.error)),this._subscription.add(this._messagesReceivedFromHistory().subscribe(this._acceptReceivedMessage("history"),(function(t){return e.logger.warn("".concat(Kx,": Failed to fetch chat history"),t)})))}},{key:"stop",value:function(){this._chatApi.stop(),this._messengerStoppedSubject.next(),this._subscription.unsubscribe()}},{key:"observables",value:function(){return{ownMessages:this._sentMessages.pipe(hb(this._receivedVisitorMessages())),operatorMessages:this._receivedOperatorMessages(),operatorTypingIndicator:this._chatApi.operatorTypingIndicator}}},{key:"_chatEvents",value:function(e){return this._chatApi[e].pipe(ev(this._messengerStoppedSubject))}},{key:"_receivedVisitorMessages",value:function(){return this._chatEvents("receivedVisitorMessages").pipe(ub(k.merge({status:vt(Yx.DELIVERED)})))}},{key:"_sendMessageAndWaitForAcknowledgement",value:function(e){var t=this,n=e.message,r=this._deliveryEvents.pipe(eb((function(e){return k.equals(n.id,e.id)})),$b(1),Fb()),i=r.subscribe(k.always);return this._chatApi.sendMessage(n).pipe(Xb(r.pipe(lb(Yx.DELIVERED),av(this._deliveryTimeout,ur("".concat(Kx,": Message timed out before being delivered to other participant"))))),Rd((function(e){return t.logger.info("".concat(Kx,": Message delivery failed with error"),{error:e,message_id:n.id}),vt(Yx.FAILED)})),$b(1),tb(i.unsubscribe))}},{key:"_sendMessage",value:function(e){var t,n,r,i,o,s,a=this,c=(t=e,n=this._generateGuid,r=t.content,i=t.options,o=i?i.attachment:void 0,s=i?i.metadata:void 0,{id:n(),content:r,attachment:o,metadata:s}),u=new fi(1).distinctUntilChanged();return u.next(Yx.SENDING),this._sentMessages.next(k.merge(c,{status:u})),this._addToReceived(c),this._subscription.add(this._sendMessageAndWaitForAcknowledgement({message:c}).subscribe((function(e){u.next(e),e===Yx.DELIVERED&&(u.complete(),a.stats.recordChatMessageDelivered(),a.logger.info("".concat(Kx,": Message delivered to other participant"),{message_id:c.id})),e===Yx.FAILED&&a.stats.recordChatMessageDeliveryFailed()}),this.logger.error))}},{key:"_acceptReceivedMessage",value:function(e){var t=this;return function(n){t.logger.info("".concat(Kx,": Message received"),{message_id:n.id,source:e}),t._addToReceived(n),k.pathEq(["sender","type"],"visitor",n)||n.delivered_at||t._chatApi.markMessageAsDelivered(n.id)}}},{key:"_receivedOperatorMessages",value:function(){var e=this;return this._chatEvents("receivedOperatorMessages").pipe(eb((function(t){return e._messageNotReceived(t)})),vb((function(t){return vt(t).pipe(nv(e._acceptReceivedMessage("participant")),Rd((function(){return vt(t)})))})),Fb())}},{key:"_messagesReceivedFromHistory",value:function(){var e=this;return this._history.pipe(eb((function(t){return e._messageNotReceived(t)})),vb((function(e){return Ft(e)})))}},{key:"_messageNotReceived",value:function(e){return!k.contains(e.id,this._receivedMessageIds)}},{key:"_addToReceived",value:function(e){this._receivedMessageIds=k.append(e.id,this._receivedMessageIds)}}]),e}();Xx.STATUSES=Yx;var $x=n.default.visitor_api.own_typing_duration||5e3;var Zx="engagement.chat.message",eA="engagement.chat.message_status",tA="engagement.chat.typing_indicator.operator",nA="engagement:chat_message:preview_update",rA="Chat",iA={retryLimit:5,initialDelay:1e3,maxDelay:void 0,factor:1.5},oA=function(e){return 0===e||421===e||429===e||e>=500},sA=function(){},aA=function(e){var t,n,r=e.engagementId,i=e.visitorId,o=e.logger,s=e.stats,a=e.channelObservable,c=e.xhrWithRetry,u=void 0===c?Ug:c,l=e.getRequestHeaders,p=e.siteVisitorNotifications,f=new Re,h=function(e){return e.attachment?{content:e.content,attachment:e.attachment}:{content:e.content}},d=(t=f.map(k.prop("content")),t.pipe(Kb((function(e){return""===e?wv.of(!1):wv.merge(wv.of(!0),wv.timer($x,n).map((function(){return!1})))})),iv(50,n,{leading:!0,trailing:!0}),Jd())).subscribe((function(e){Lg({method:"PUT",url:"".concat(sm.conf.api_url,"/engagements/").concat(r,"/typing_indicator"),payload:JSON.stringify({typing:e}),responseType:"json",getRequestHeaders:function(){return k.merge(l?l():{},{"Content-Type":"application/json"})},onSuccess:sA,onError:function(e){return o.warn("Could not set typing indicator",e)},onAttempt:sA,shouldRetry:function(){return!1}})})),b=f.startWith({content:""}).combineLatest(a).subscribe((function(e){var t=g(e,2),n=t[0];t[1].emit(nA,{engagement_id:r,content:n.content,visitor_id:i})}),o.error.bind(o,"".concat(rA,": Error sending chat preview"))),v=k.compose(k.merge({type:"user"}),k.pick(["id","engagement_id","content","attachment","metadata","sender"]),k.prop("message")),m=k.compose(k.pick(["id","engagement_id"]),k.prop("message")),y=k.propEq("event_type",Zx),_=k.propEq("event_type",eA),w=k.pathEq(["message","engagement_id"],r),E=["message","sender","type"],O=k.pathEq(E,"operator"),S=k.pathEq(E,"visitor"),T=k.pathEq(["message","status"],"delivered"),x=p.pipe(eb(k.allPass([y,w]))),I=x.pipe(eb(O),ub(v)),N=x.pipe(eb(S),ub(v)),C=p.pipe(eb(k.allPass([_,w,T])),ub(m)),R=k.propEq("event_type",tA),P=k.pathEq(["typing_indicator","engagement_id"],r);return{stop:function(){b.unsubscribe(),d.unsubscribe()},sendMessage:function(e){var t=e.id;return Ee.create((function(n){var i=0;u({method:"PUT",url:"".concat(sm.conf.api_url,"/engagements/").concat(r,"/chat_messages/").concat(t),payload:JSON.stringify(h(e)),responseType:"json",contentType:"application/json",getRequestHeaders:l,calculateAttemptDelay:A(iA.initialDelay,iA.maxDelay,iA.factor),retryLimit:iA.retryLimit,onSuccess:function(t){o.info("".concat(rA,": Message sent to system, waiting for it to be delivered to other participant"),{message_id:e.id}),n.next(t),n.complete()},onError:function(e){var r=e.status,i=e.statusText,s="".concat(rA,": Failed to send message to system");o.warn(s,{message_id:t,status:r,status_text:i}),n.error(s)},onAttempt:function(){++i>1&&o.info("Chat: Send message request failed, retrying",{message_id:t,attempt:i}),s.recordChatMessageSent(i)},shouldRetry:oA})})).pipe($b(1))},sendPreview:function(e){return f.next(e)},markMessageAsDelivered:function(e,t,n){u({method:"PATCH",url:"".concat(sm.conf.api_url,"/engagements/").concat(r,"/chat_messages/").concat(e),payload:JSON.stringify({status:"delivered"}),responseType:"json",contentType:"application/json",getRequestHeaders:l,calculateAttemptDelay:A(iA.initialDelay,iA.maxDelay,iA.factor),retryLimit:iA.retryLimit,onSuccess:function(){o.info("".concat(rA,": Marked message as delivered"),{message_id:e}),"function"==typeof t&&t()},onError:function(t){var r=t.status,i=t.statusText;o.warn("".concat(rA,": Failed to mark message as delivered"),{message_id:e,status:r,status_text:i}),"function"==typeof n&&n()},shouldRetry:oA})},receivedOperatorMessages:I,receivedVisitorMessages:N,deliveredMessages:C,operatorTypingIndicator:p.pipe(eb(k.allPass([R,P])),ub(k.prop("typing_indicator")),Db((function(e,t){return t.clock>e.clock?t:e})),ub(k.pick(["typing"])),Jd(k.equals))}},cA=function(e,t){for(var n,r=[];n=t.exec(e);)r.push(n[1]);return r},uA=function(e,t,n){return t&&k.forEach((function(t){var r=t.split("").join(".*?");e=e.replace(new RegExp(r),n)}),t),e},lA=function(e){var t=!0;return e.split("").reduceRight((function(e,n){return n=parseInt(n,10),(t=!t)&&(n*=2),n>9&&(n-=9),e+n}),0)%10==0},pA=k.compose((function(e){var t=new RegExp(/(?:^|\D)(\d{3}(-| )\d{2}(-| )\d{4})(?=\D|$)/g),n=cA(e,t);return uA(e,n,"***Social Security Number Not Allowed***")}),(function(e){var t=new RegExp("(\\d{".concat(12,",})"),"g"),n=cA(function(e){var t=new RegExp("([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})|([^(a-zA-Z0-9)])","gm");return e.replace(t,"$1")}(e),t),r=k.filter(lA,n);return uA(e,r,"***Credit Card Number Not Allowed***")}),(function(e,t){return t.reduce((function(e,t){try{var n=new RegExp(t,"g");return e.replace(n,(function(e){return"*".repeat(e.length)}))}catch(t){return e}}),e)})),fA=function(e){return e.replace(/[0-9]/g,"*")},hA=function(){function e(t){var n=t.channelObservable,r=t.historyObservable,i=t.getRequestHeaders,o=t.logger,a=t.statsClient,c=t.engagementId,u=t.visitorId,l=t.siteVisitorNotifications,p=t.maskingRegularExpressions;s(this,e);var f=new Qx(a);this._messagesToSend=new Re,this._previewToSend=new Re,this.chatApi=new aA({engagementId:c,visitorId:u,logger:o,stats:f,channelObservable:n,getRequestHeaders:i,siteVisitorNotifications:l}),this.messenger=new Xx({chatApi:this.chatApi,stats:f,logger:o,messagesToSend:this._messagesToSend.pipe(ub((function(e){return function(e,t){var n=e.content,r=e.options;return{content:pA(n,t),options:r}}(e,p)}))),previewToSend:this._previewToSend.pipe(ub(fA)),history:r}),this.messenger.start()}return c(e,[{key:"sendMessage",value:function(e,t){this._messagesToSend.next({content:e,options:t})}},{key:"sendMessagePreview",value:function(e){this._previewToSend.next(e)}},{key:"stop",value:function(){this.messenger.stop()}},{key:"observables",value:function(){return this.messenger.observables()}}]),e}(),dA=function(){function e(t){var n=t.chatHistoryObservable,r=t.engagementEndObservable,i=t.observeChatMessages,o=t.statsClient,a=t.chatController,c=t.fetchExtraOperatorInfo;s(this,e);var u=new se,l=Qg(),p=a.observables(),f=p.operatorMessages,h=p.ownMessages,d=p.operatorTypingIndicator,b=i({chatHistoryObservable:n,operatorMessages:f,ownMessages:h,statsClient:o,fetchExtraOperatorInfo:c}),v=b.messages.pipe(Ib(1)),m=b.messagesWithStatusUpdates.pipe(Ib(1));u.add(v.connect()),u.add(m.connect());var y=d.pipe(ub(k.construct(zx)),Qb(new zx({typing:!1})),Ib(1));u.add(y.connect());var g=function(){l.stop(),u.unsubscribe()},_=k.fromPairs([[this.EVENTS.MESSAGES,v],[this.EVENTS.MESSAGES_WITH_STATUS_UPDATES,m],[this.EVENTS.OPERATOR_TYPING_STATUS_UPDATE,y]]);l.proxyAll(_),this.addEventListener=l.addEventListener,this.removeEventListener=l.removeEventListener,this.observable=function(e){return _[e]},this.sendMessage=function(e,t){a.sendMessage(e,t),a.sendMessagePreview("")},this.sendMessagePreview=function(e){a.sendMessagePreview(e)},r.subscribe((function(){}),g,g)}return c(e,null,[{key:"create",value:function(t){var n=t.chatHistoryObservable,r=t.engagementEndObservable,i=t.statsClient,o=t.engagementId,s=t.getRequestHeaders,a=t.siteVisitorNotifications,c=t.maskingRegularExpressions,u=bm.vent.observable(bm.MSG.PUBLIC.ENGAGEMENT_START),l=Ee.defer((function(){return bm.request("get:engagement_observables").engagementObservable})),p=function(e){var t=e.getRequestHeaders,n=e.xhrWithRetry,r=void 0===n?Ug:n,i=e.takeUntilNotifier,o={},s={},a=i||new Gv.Subject;return function(e){return o[e]?vt(o[e]):Ee.create((function(n){if(s[e])s[e].push(n);else{s[e]=[n];var i=function(e){return function(){s[e]&&(s[e].forEach((function(e){e.next(),e.complete()})),delete s[e])}}(e);r({method:"GET",url:"".concat(sm.conf.api_url,"/operators/").concat(e,"?include_engagements=false"),responseType:"json",contentType:"application/json",getRequestHeaders:t,onSuccess:function(t){o[e]=t.response,s[e]&&(s[e].forEach((function(e){e.next(t.response),e.complete()})),delete s[e]),delete s[e]},onError:i,shouldRetry:function(){return!1}})}})).pipe(ev(a))}}({getRequestHeaders:s}),f=function(e){var t=e.chatHistoryObservable,n=e.engagementStartObservable,r=e.engagementObservables,i=e.siteVisitorNotifications,o=e.getRequestHeaders,s=e.statsClient,a=e.engagementId,c=e.maskingRegularExpressions,u=n.pipe(mb(r),Tb("channel"),Ib(1)),l=u.connect(),p=new hA({channelObservable:u,historyObservable:t,getRequestHeaders:o,statsClient:s,logger:sm.logger.withTags({engagement_id:a,site_id:sm.siteId}),engagementId:a,visitorId:Jv(),siteVisitorNotifications:i,maskingRegularExpressions:c});return{chatController:p,stopChat:function(){p.stop(),l.unsubscribe()}}}({chatHistoryObservable:n,engagementStartObservable:u,siteVisitorNotifications:a,engagementObservables:l,statsClient:i,engagementId:o,getRequestHeaders:s,maskingRegularExpressions:c}),h=f.chatController,d=f.stopChat;return{chat:new e({chatHistoryObservable:n,engagementEndObservable:r,observeChatMessages:Gx,statsClient:i,chatController:h,fetchExtraOperatorInfo:p}),stopChat:d}}}]),e}();dA.prototype.EVENTS={MESSAGES:"messages",MESSAGES_WITH_STATUS_UPDATES:"messages-with-status-updates",OPERATOR_TYPING_STATUS_UPDATE:"operator-typing-status-update"},dA.prototype.SENDERS=Vx;var bA={OBSERVATION:"OBSERVATION",ENGAGEMENT:"ENGAGEMENT",POINTER:"POINTER"},vA=function(){function e(t,n){s(this,e),this.mode=t,this.session=n}return c(e,null,[{key:"createObservation",value:function(){return new this(bA.OBSERVATION,null)}},{key:"createActive",value:function(e){return new this(e.mode,e.session)}}]),e}(),mA=function(){function e(t){var n=t.cobra;s(this,e),this.stop=function(){return n.switchToObservation()}}return c(e,[{key:"stop",value:function(){}}]),e}(),yA=function(){function e(t){var n=t.operator,r=t.channel;s(this,e),this.operator=n,this.allow=function(){return r.emitAll("engagement:offer_cobrowsing:allow"),nm.info("Visitor accepted cobrowsing request"),null},this.decline=function(){return r.emitAll("engagement:offer_cobrowsing:deny"),nm.info("Visitor declined cobrowsing request"),null}}return c(e,[{key:"allow",value:function(){}},{key:"decline",value:function(){}}]),e}(),gA=function e(t){var n=this,r=t.cobra,i=t.operator,o=t.channelObservable,a=t.fromRxJs4,c=void 0===a?ey:a;s(this,e);var u=o.switchMap((function(e){var t=e.channel;return t.emitAll("engagement:offer_cobrowsing:ready"),t.observable("engagement:offer_cobrowsing:offer_cobrowsing").do((function(){return t.emitAll("engagement:offer_cobrowsing:ack")})).map(k.always({channel:t}))})).do((function(){return nm.info("Received cobrowsing request")})).share().map((function(e){var t=e.channel;return new yA({operator:i,channel:t})})),l=c(r.modeObservable.pluck("name").map((function(e){return e===n.MODES.OBSERVATION?vA.createObservation():vA.createActive({mode:e,session:new mA({cobra:r})})}))),p=k.fromPairs([[this.EVENTS.COBROWSING_REQUEST,u],[this.EVENTS.MODE_CHANGE,l]]),f=Yg(),h=Qg();h.proxyAll(p),f.proxyAll(p),this.resendPage=function(){"function"==typeof r.resendPage&&r.resendPage()},this.addUnbufferedEventListener=h.addEventListener,this.removeUnbufferedEventListener=h.removeEventListener,this.addBufferedEventListener=f.addEventListener,this.removeBufferedEventListener=f.removeEventListener,this.observable=function(e){return h.observable(e)},this.bufferedObservable=function(e){return f.observable(e)}};gA.prototype.EVENTS={COBROWSING_REQUEST:"cobrowsing_request",MODE_CHANGE:"cobrowser_mode_change"},gA.prototype.MODES=bA;var _A=function(e){return"browser"===e?"audio":"phone"},wA=function(e){var t=e.upgradeRequest,n=e.currentMediaState,r={audio:k.path(["audio","direction"],n),video:k.path(["video","direction"],n)},i=k.pick(["audio","video"],t),o=k.invert(r).two_way||[],s=k.invert(i).two_way||[];return!k.isEmpty(k.difference(s,o))},EA="two_way",OA="one_way",SA=function(e,t){return k.maxBy((function(e){return e===EA?2:e===OA?1:0}),e,t)},TA=function(e){if(e){if(e.video)return"video";if(e.audio&&"browser"===e.audio.type)return"audio";if(e.audio&&"phone"===e.audio.type)return"phone"}return"text"},kA=function(e){return e.stateObservable.bufferCount(2,1).filter((function(e){var t=g(e,2),n=t[0],r=t[1];return n.sub_engagement_id!==r.sub_engagement_id})).do(nm.log.bind(nm,"Detect sub_engagement change")).map((function(e){var t=g(e,2);t[0];return t[1]})).map((function(e){var t=new ik({id:e.operator.id,name:e.operator.name||"Operator",formattedName:e.operator.formatted_name,picture:{url:e.operator.picture_url},media_type:e.operator.media_type}),n={id:e.id,subEngagementId:e.sub_engagement_legacy_id,channelUrl:e.channel_url,mediaState:e.media_state,operatorId:t.getId(),operatorName:t.getName(),operatorFormattedName:t.getFormattedName(),operatorPicture:t.getPictureUrl(),operatorMedia:t.getMediaType()};return n=k.assoc("startingMedia",TA(n),n)})).map(k.pick(["operatorId","operatorName","operatorFormattedName","operatorPicture","operatorMedia","startingMedia","subEngagementId","id"])).map(k.merge({isReestablishing:!1,isTransfer:!0})).do(nm.log.bind(nm,"Engagement transferred"))},xA=function(e){var t,n=e.engagement,r=e.transfers,i=e.channelObservable,o=e.webRtcMode,s=e.statusObservable,a={id:n.engagementId,subEngagementId:n.subEngagementId,startingMedia:n.startingMedia,isReestablishing:n.isReestablishing,operatorId:n.operator.id,operatorName:n.operator.name,operatorFormattedName:n.operator.formattedName,operatorPicture:n.operator.picture?n.operator.picture.url:void 0,operatorMedia:(t=n.operator.state.medias,k.findLast(k.contains(k.__,t),$y)),observable:n.observable.bind(n),EVENTS:n.EVENTS},c=s.filter(k.propEq("interaction","engagement")).map(k.prop("channelUrl")).take(1),u=i.switchMap((function(e){var t=e.channel;return c.map((function(e){return{channel:t,engagementChannelUrl:e}}))})).filter((function(e){var t=e.channel,n=e.engagementChannelUrl;return t.url===n})).take(1);return Gv.Observable.of(a).merge(r).switchMap((function(e){return u.map((function(t){var n=t.channel;return k.merge({channel:n},e)}))})).map(k.evolve({startingMedia:k.when(k.isNil,k.always(n.startingMedia))})).map((function(e){return k.merge(e,{webRtcMode:o})}))};function AA(e){return k.reduce((function(e,t){return e.then((function(e){return t.then((function(t){return k.append(t,e)}))}))}),Promise.resolve([]),e)}var IA=k.compose(k.join(", "),k.map((function(e){return"'".concat(e,"'")}))),NA=/^\+?[1-9]\d{1,14}$/,CA=function(e){return new Promise((function(t,n){return function(e){return Boolean(e&&e.phoneNumber)}(e)?(r=e.phoneNumber,NA.test(r)?void t():n(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Invalid phone number: '".concat(e.phoneNumber,"'! Make sure that country code is present in the number and it has plus sign (+) prefix")}))):n(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"'phone' was specified as the media but the 'phoneNumber' option is missing!"}));var r}))},RA=function(e){return new Promise((function(t,n){if(function(e){return e&&e.hasOwnProperty("phoneExtension")}(e)&&(null!==(r=e.phoneExtension)&&!r.match(/^(,*\d,*){1,7}$/)))return n(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Invalid phone extension: '".concat(e.phoneExtension,"'! The phone extension can only contain commas and up to 7 digits.")}));var r;t()}))},PA=function(e){var t=e.media,n=e.options,r=e.availableMediaTypes,i=e.availableOneWayMediaTypes,o=e.visitorUpgradesAllowed,s=e.highestAllowedMediaType,a=[],c=!1===o?k.drop(r.indexOf(s),r):r;return a.push(function(e,t,n,r,i){return new Promise((function(o,s){if(i.oneWay){if(!1===r)return s(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"This site does not support 'one-way' option!"}));if(!k.contains(e,n))return s(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Media must be one of: ".concat(IA(n),"!")}))}if(!i.oneWay&&!k.contains(e,t))return s(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Media must be one of: ".concat(IA(t),"!")}));o()}))}(t,c,i,o,n||{})),"phone"===t&&(a.push(CA(n)),a.push(RA(n))),AA(a)},MA=function(e){var t=e.options,n=e.availableMediaTypes,r=e.availableOneWayMediaTypes,i=e.visitorUpgradesAllowed,o=e.highestAllowedMediaType,s=[],a=!1===i?k.drop(n.indexOf(o),n):n;return s.push(function(e,t,n,r){return new Promise((function(i,o){if(e.audio){var s=["browser","phone"];if(!k.contains(e.audio,s))return o(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Audio must be one of: ".concat(IA(s),"!")}));if(!k.contains("audio",t)&&!k.contains("phone",t))return o(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Audio is not supported!"}))}if(e.video){var a=["one_way","two_way"];if(!k.contains(e.video,a))return o(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Video must be one of: ".concat(IA(a),"!")}));if("one_way"===e.video&&!1===r)return o(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"This site does not support 'one-way' option!"}));if("one_way"===e.video&&!k.contains("video",n))return o(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"One-way video is not supported!"}));if("two_way"===e.video&&!k.contains("video",t))return o(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Video is not supported!"}))}i()}))}(t,a,r,i)),"phone"===t.audio&&(s.push(CA(t)),s.push(RA(t))),AA(s)},jA=function e(t){var n=this;s(this,e);var r=t.visitor,i=t.operator;this.visitor=k.compose(k.evolve({phoneStatus:function(e){switch(e){case bm.MSG.PHONE_STATUSES.CONNECTED:return n.PHONE_STATUSES.CONNECTED;case bm.MSG.PHONE_STATUSES.CONNECTING:return n.PHONE_STATUSES.CONNECTING;default:return n.PHONE_STATUSES.UNUSED}}}),k.pickAll(["media","audioMuted","videoMuted","phoneStatus"]))(r),this.operator=k.pickAll(["media","audioMuted","videoMuted"],i)};jA.prototype.PHONE_STATUSES={CONNECTED:"connected",CONNECTING:"connecting",UNUSED:"unused"};var LA=function e(t){var n=t.id,r=t.label,i=t.is_default,o=t.position;if(s(this,e),this.id=n,this.label=r,this.is_default=i,this.position=o,!this.id||!this.label)throw nm.error("Survey choice missing parameters",{parameters:{id:n,label:r,is_default:i,position:o}}),new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR,message:"Survey choice is missing required parameters"})},qA=function e(t){var n=this,r=t.id,i=t.text,o=t.name,a=t.type,c=t.required,u=t.position,l=t.options;s(this,e),this.id=r,this.text=i,this.name=o,this.type=a,this.required=c,this.position=u,this.options=l;var p=function(){return n.options&&Array.isArray(n.options)&&!k.isEmpty(n.options)};if("single_choice"===this.type&&p()&&(this.options=this.options.map((function(e){return new LA(e)}))),"single_choice"!==this.type||p()||nm.warn("Single choice survey question missing options",{parameters:arguments[0]}),!(this.id&&this.text&&this.name&&this.type))throw nm.error("Survey question missing parameters",{parameters:arguments[0]}),new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR,message:"Survey question is missing required parameters"})},UA=function e(t,n){var r=this,i=t.survey;s(this,e),this.id=i.id,this.description=i.description,this.title=i.title,this.type=i.type,this.name=i.name,this.questions=i.questions.map((function(e){return new qA(e)})).filter((function(e){return!(e.type===r.QUESTION_TYPES.SINGLE_CHOICE&&k.isEmpty(e.options))})),this.answer=function(e){return n({surveyId:i.id,answers:Gy(e)})}};UA.prototype.QUESTION_TYPES={BOOLEAN:"boolean",SCALE:"scale",TEXT:"text",SINGLE_CHOICE:"single_choice"};var DA=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),VA=["#inner-page",".socketio","script[src*='".concat(n.default.assets.server,"']"),"#cobrowsing-mouse-container","style[data-page-iframer='keep']"],FA=n.default.visitor_app.is_custom_theme?["body > link","head > link"]:["link[href*='".concat(n.default.assets.server,"']"),"link[href*='".concat(n.default.api_url,"']"),"link[href*='https://uploads.salemove.com']"],BA=VA.concat(FA),HA=function(){function e(t,n){s(this,e),this._retainedElementsBySelector=this._retainedElementsBySelector.bind(this),this._document=t,n||(n=[]),this._filters=n}return c(e,[{key:"clean",value:function(){this._removeAccordingToFiltersLeavingTopLevelInPlace(),this._cleanHtmlElementOfUnnecessaryAttributes(),this._overrideBodyInlineStyles(),this._hideParentsOfKeptHiddenElements()}},{key:"_removeAccordingToFiltersLeavingTopLevelInPlace",value:function(){var e=k.chain(this._retainedElementsBySelector,this._filters),t=Hm(this._document.head.querySelectorAll("*")).concat(Hm(this._document.body.querySelectorAll("*")));return k.differenceWith(k.identical,t,e).filter((function(e){return"title"!==e.localName})).map((function(e){return e.parentNode.removeChild(e)}))}},{key:"_retainedElementsBySelector",value:function(e){var t=Hm(this._document.querySelectorAll(e));return k.chain((function(e){return Hm(e.querySelectorAll("*")).concat([e]).concat(Bm(e))}),t)}},{key:"_cleanHtmlElementOfUnnecessaryAttributes",value:function(){var e=this._document.querySelector("html");Hm(e.attributes).filter((function(e){return"lang"!==e.name})).forEach((function(t){return e.removeAttribute(t.name)}))}},{key:"_overrideBodyInlineStyles",value:function(){this._document.body.removeAttribute("style")}},{key:"_hideParentsOfKeptHiddenElements",value:function(){if(this._filters.length>0){var e=Hm(this._document.body.querySelectorAll("*")).filter(Fm),t=Hm(this._document.body.querySelectorAll(this._filters.join(","))),n=k.chain((function(e){var t=Hm(e.querySelectorAll("*")).concat([e]);return Fm(e)?t.concat(Bm(e)):t}),t);k.differenceWith(k.identical,e,n).forEach((function(e){e.style.display="none"}))}}}]),e}(),WA=sm.conf.visitor_app.css_prefix||"sm-",GA={id:"inner-page",getTargetUrl:function(){return window.location.href},document:window.document,nonRemoved:[]},zA=function(){function e(t){s(this,e);var n=k.merge(GA,t);this._id=n.id,this._targetUrl=n.getTargetUrl(),this._targetDocument=n.document||window.document,this._iframeElement=this._createIframeElement(this._targetDocument);var r=(n.nonRemoved||[]).concat(["#".concat(this._id)]).concat(BA);this._cleaner=new HA(this._targetDocument,r),this._iframeTargetPointer=n.targetId,this._wrapIframe=n.wrapIframe}return c(e,[{key:"putIntoIframe",value:function(){var e=this;return new Promise((function(t,n){var r=Sx(e._targetDocument);return e._iframeElement.style.visibility="hidden",e._callWhenIframeLoaded((function(){return e._iframeElement.style.visibility="",Ox(e._iframeElement.contentDocument,r),e._clearCurrentDom(),t({iframe:e._iframeElement})})),e._insertIframe()}))}},{key:"_clearCurrentDom",value:function(){return this._cleaner.clean()}},{key:"_createIframeElement",value:function(e){var t=e.createElement("iframe");return t.setAttribute("id",this._id),t}},{key:"_insertIframe",value:function(){var e;this._iframeElement.src=this._targetUrl,this._ensureBodyExists();var t=this._iframeSiblingElement();if(this._wrapIframe){var n=this._targetDocument.createElement("div");n.setAttribute("id","".concat(WA,"inner-page-wrapper")),n.appendChild(this._iframeElement),e=n}else e=this._iframeElement;t?this._targetDocument.body.insertBefore(e,this._iframeSiblingElement()):this._targetDocument.body.appendChild(e),this._iframeElement.contentWindow.location.href=this._targetUrl}},{key:"_iframeSiblingElement",value:function(){if(this._iframeTargetPointer)return this._targetDocument.getElementById(this._iframeTargetPointer)}},{key:"_callWhenIframeLoaded",value:function(e){return this._iframeElement.addEventListener("load",(function t(n){return n.target.removeEventListener("load",t),e()}))}},{key:"_ensureBodyExists",value:function(){if(!this._targetDocument.body){var e=this._targetDocument.createElement("body");return this._targetDocument.appendChild(e)}}}]),e}(),JA="sm-wrapped-page",QA=function(){function e(t){var n=t.document,r=t.nonRemoved;s(this,e),this.wrap=this.wrap.bind(this),this.unwrap=this.unwrap.bind(this),this.document=n,this.nonRemoved=(r||[]).concat(["#".concat(this._id)]).concat(BA)}return c(e,[{key:"wrap",value:function(){var e=this._createWrappingDiv(),t=this.nonRemoved.join(", ");Hm(this.document.body.children).forEach((function(n){Wm(n,t)||Wm(n,"iframe")&&"none"===window.getComputedStyle(n).display||e.appendChild(n)}));var n=this.document.body.children[0];this.document.body.insertBefore(e,n)}},{key:"unwrap",value:function(){var e=this.document.getElementById(JA);e&&(Hm(e.children).forEach((function(t){e.parentNode.appendChild(t)})),e.parentNode.removeChild(e))}},{key:"_createWrappingDiv",value:function(){var e=this.document.createElement("div");return e.id=JA,e.className=JA,e}}]),e}(),YA=function e(t){var n=t.media,r=t.medias;s(this,e),this.media=n,this.medias=r},KA=function(e,t){"iframe"===e?document.querySelector("#inner-page").contentWindow.location.assign(t):window.location.href=t},XA=function(e){var t=e.volatileNotifications,n=e.visitorPageAdaption;return t.filter(k.both(k.propEq("site_id",sm.siteId),k.propEq("event","navigation_to_url"))).map(k.prop("payload")).subscribe(KA.bind(this,n),nm.error.bind(nm,"Unable to navigate to url"))},$A=function e(t){var n=t.medraStream;s(this,e),this.stream=n.getWebMediaStream()},ZA=function(){function e(t){var n=t.medraStream,r=t.connection;s(this,e),n.getWebMediaStream().getVideoTracks()[0].onended=function(){return r.stop()},this.stopSharing=function(){return r.stop(),null}}return c(e,[{key:"stopSharing",value:function(){}}]),e}(),eI=function e(t){var n=t.status,r=t.screen;s(this,e),this.status=n,this.screen=r};eI.prototype.STATUSES={SHARING:"sharing",NOT_SHARING:"not_sharing"};var tI=function e(t){var n=t.status,r=t.screen;s(this,e),this.status=n,this.screen=r};tI.prototype.STATUSES={SHARING:"sharing",NOT_SHARING:"not_sharing"};var nI=function e(t){var n=t.onAccept,r=t.onDecline;s(this,e),this.accept=function(){return n().then((function(){return{}}))},this.decline=function(){r()}},rI=function(){return{mediaDevices:navigator.mediaDevices}},iI=function(e){var t,n=e.conf,r=e.channelObservable,i=e.namespace,o=e.videoProvider;return dm("Medra").map(k.prop("default")).map((function(e){return new e({webRTC:{iceServers:n.communications.webrtc_server,videoProvider:o}})})).flatMap((function(e){return r.do((function(){t&&(sm.logger.info("Stopping Medra connection due to new channel"),t.stop())})).flatMap((function(t){var n=t.channel;return Zm(e.connect(n,{namespace:i}))})).do((function(e){t=e}))}))},oI=function(){function e(t){var n=t.adapter,r=t.operatorScreenSharedObservable,i=t.visitorScreenSharedObservable,o=t.screenShareRequestedObservable;s(this,e),this.EVENTS={OPERATOR_STATE_UPDATE:"operator_state_update",VISITOR_STATE_UPDATE:"visitor_state_update",SCREEN_SHARING_REQUEST:"screen_sharing_request"};var a=k.fromPairs([[this.EVENTS.OPERATOR_STATE_UPDATE,r],[this.EVENTS.VISITOR_STATE_UPDATE,i],[this.EVENTS.SCREEN_SHARING_REQUEST,o]]);n.proxyAll(a),this.addBufferedEventListener=n.addEventListener,this.removeBufferedEventListener=n.removeEventListener}return c(e,null,[{key:"start",value:function(t){var n,r,i=t.conf,o=t.channelObservable,s=t.connectMedra,a=t.fromRxJs5,c=t.scheduler,u=t.videoProvider,l=t.isReestablishing,p=t.stats;a||(a=Zm),s||(s=iI);var f=new Gv.Subscription,h=new Gv.Subject,d=new Gv.Subject;u||(u=function(e,t){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:rI()).mediaDevices;return{getStream:function(){return new Promise((function(r,i){t.next(new nI({onAccept:function(){nm.info("Requesting screen capture");var t=e.statScreenShareUsage({stage:"capture",resource:"visitor_api.screen_sharing"}).attempted();return n.getDisplayMedia({video:!0}).then((function(e){r(e),t.succeeded(),nm.info("Screen capture successful")})).catch((function(e){return i(e),"NotAllowedError"===e.name?(nm.info("Screen capture permissions denied",e),t.failed("canceled"),Promise.reject(new ag({cause:Ky.SALEMOVE.CANCEL}))):(t.failedUnknown(),Promise.reject(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR})))}))},onDecline:function(){sm.logger.info("Screen sharing request declined"),i({name:"NotAllowedError"})}}))}))}}}(p,d));var b=new Gv.Subject,v=b.switchMap((function(){return s({conf:i,channelObservable:o,namespace:"visitor-screensharing",videoProvider:u})})).publishReplay(1);if(f.add(v.connect()),b.next({}),v.switchMap((function(e){return a(e.communicationRequest).map((function(t){return{proposal:t,connection:e}}))})).subscribe((function(e){var t=e.proposal,n=e.connection,r=p.statScreenShareUsage({stage:"sharing",resource:"visitor_api.screen_sharing"}).attempted();return t.accept({video:{type:"browser"}}).then((function(e){var t=e.localVideoStream;r.succeeded(),sm.logger.info("Screen sharing succeeded"),h.next({connection:n,localVideoStream:t})})).catch((function(e){e&&e.cause===n.ERRORS.PERMISSIONS_DENIED?(r.failed("canceled"),sm.logger.info("Screen sharing canceled")):e&&e.cause===n.ERRORS.DEVICE_ACCESS_ERROR?(r.failed("device_access_error"),sm.logger.warn("Screen sharing failed due to device access error",e)):(r.failedUnknown(),sm.logger.warn("Screen sharing failed",e))}))}),sm.logger.error.bind(sm.logger,"Failed to receive screen sharing request")),l){f.add(v.take(1).subscribe((function(e){return e.reestablish().then((function(t){var n=t.localVideoStream;if(n)return h.next({connection:e,localVideoStream:n})}))}),sm.logger.error.bind(sm.logger,"Failed to reestablish visitor screen")))}var m=new eI({status:eI.prototype.STATUSES.NOT_SHARING}),y=(n=s({conf:i,channelObservable:o,namespace:"operator-screensharing"}).switchMap((function(e){var t=a(e.communicationRequest).flatMap((function(t){return Gv.Observable.fromPromise(t.accept({})).catch((function(t){return t&&t.cause===e.ERRORS.REMOTE_PARTICIPANT_ERROR?sm.logger.info("Failed to receive operator screen due to error on operator side",t):sm.logger.warn("Failed to receive operator screen",t),Gv.Observable.empty()}))}));return l?Gv.Observable.merge(Gv.Observable.fromPromise(e.reestablish()),t).filter((function(e){var t=e.remoteVideoStream;return!k.isNil(t)})):t})).do((function(){return sm.logger.info("Remote screen sharing stream received")})).flatMap((function(e){var t=e.remoteVideoStream,n=Gv.Observable.defer((function(){var e="playing"===t.getMediaState()?eI.prototype.STATUSES.SHARING:eI.prototype.STATUSES.NOT_SHARING;return Gv.Observable.of(new eI({screen:new $A({medraStream:t}),status:e}))})),r=a(t.observe(t.EVENTS.DISCONNECTED)).map((function(){return m}));return Gv.Observable.merge(n,r)}))).startWith.apply(n,_([m,c].filter(k.identity))),g=new tI({status:tI.prototype.STATUSES.NOT_SHARING}),w=null,E=(r=h.do((function(){return sm.logger.info("Screen sharing request accepted")})).switchMap((function(e){var t=e.localVideoStream,n=e.connection;w=new ZA({medraStream:t,connection:n});var r=Gv.Observable.of(new tI({screen:w,status:tI.prototype.STATUSES.SHARING})),i=a(t.observe(t.EVENTS.DISCONNECTED)).do((function(){return b.next({})})).map((function(){return g}));return Gv.Observable.merge(r,i)}))).startWith.apply(r,_([g,c].filter(k.identity))).share(),O=Yg();return{screenSharing:new e({adapter:O,operatorScreenSharedObservable:y,visitorScreenSharedObservable:E,screenShareRequestedObservable:d}),stopScreenSharing:function(){w&&w.stopSharing(),O.stop(),f.unsubscribe()}}}}]),e}(),sI=function e(t){var n=t.id,r=t.properties;s(this,e),this.id=n,this.properties=r},aI=function(){return"iframe"===sm.conf.visitor_app.visitor_page_adaption},cI=function(){return aI()?document.getElementById("inner-page").contentWindow.document:document},uI=function(e){try{var t=cI();return aI()?t.body.querySelector(e):t.querySelector(e)}catch(e){return nm.info("Target element not found",{error:e}),null}},lI="virtual_assistant_cobrowsing_cursor",pI="virtual_assistant_cobrowsing_cursor_label",fI=function(e,t){var n=uI("#"+lI);if(!n){var r=function(){var e=cI().createElement("div");return e.setAttribute("id",lI),e.style.display="none",e.style.opacity="0",e.style.position="absolute",e.style.zIndex="10",e.style.top="0",e.style.left="0",e.style.width="20px",e.style.height="20px",e.style.backgroundRepeat="no-repeat",e.style.backgroundImage="url('data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAAAXNSR0IArs4c6QAAAiNJREFUKBV1kl9oUlEcx39eR21JEAwEHQQ9OKcr2mDoemgsfV5vSdFLqzEu9NSo6MHF8iUIevRBtJfyrdjbarVQF8un7ELWnKUiNzFw88+qqyL3evoe22LG/MGHe87vfL+/37nnHGprWpLtRSKROE9EAugdrVZL8ly+yhYX7zNN01rRaHQa6t6mRqPxaWraxSBi0dg6U1W1GQgEzvQ0wbApijc7Bm56tfqaIbfj9XpPYa4D3dFsNtPXb8z/M2CVRSIxpiiK7Ha7BzHvNsGQ/d8ADUsmP7NqtSrBYDjYQtDpdIf8ICOnc5JKpe2xWq0Wg2Fg38TFffuTg996/Tc5HA4qFn9MVCqVVaz183Vu0PPBYbG7WyO73UbfMtmpQqHwFJr+PuFvdOkFvZ4eLPkI90Ky/J0aikJDZvOlcql0gm8H8EMiWli4Tfl8npaXX9Ds7DVaW3uTbbfVejaXPappKplNpkHCRVUsVjsTBH3ngZR3yp0jttlsLBgMbqEO30oQBMBDgRjT37t7h95vbJAoih9WXq7knJPnKJVK0bBl2OrxeH5B+G6PNLXRgpf2+/2bSD43Go3hjwmp08U6YmOyLOeQHwMmMER4cSyXychcDB6DOVT/Mjp6umMKhZ4wn88nIn8ckPA2Erl1dnz8GcbbIAHWw+Hwo1AwRAPHDCRJErlcrivIG4EAyALmwRwYAUfAyXg8Hi0Wiq2vW+mfF2dmeMELwPAHu44LBYcnDWwAAAAASUVORK5CYII=')",e}(),i=function(e,t){var n=cI().createElement("div");return n.setAttribute("id",pI),n.style.display="inline-block",n.style.color="#ffffff",n.style.fontSize="13px",n.style.padding="2px 12px",n.style.margin="18px 0 0 14px",n.style.boxShadow="1px 1px 4px rgba(50, 50, 50, 0.75)",n.style.border="1px solid #ffffff",n.style.borderRadius="4px",n.style.backgroundColor="#232323",n.style.whiteSpace="nowrap",n.innerText=t,n}(0,t);r.appendChild(i),n=cI().body.appendChild(r)}return n.style.display="block",Gv.Observable.of({cursor:n})},hI=function(e){return function(t){var n=t.interval.value+1;e.style.left=function(e,t){return(t=e.cursorInitialPosLeft-e.cursorDistanceDiffLeft*t/e.totalCircleSteps).toFixed(0)}(t,n)+"px",e.style.top=function(e,t){return(t=e.cursorInitialPosTop-e.cursorDistanceDiffTop*t/e.totalCircleSteps).toFixed(0)}(t,n)+"px"}},dI=function(e,t){var n=10*t;e.style.left=function(e,t){return(e+3*Math.cos(t*Math.PI/180)).toFixed(0)}(e.offsetLeft,n)+"px",e.style.top=function(e,t){return(e-3*Math.sin(t*Math.PI/180)).toFixed(0)}(e.offsetTop,n)+"px"},bI=function(e){return e||(e={moveCursorToPosition:hI,moveFrequency:20}),function(t){var n,r,i,o=t.cursor.offsetLeft,s=t.cursor.offsetTop,a=(n=t.targetElement,r=n.getBoundingClientRect(),i=r.top+cI().documentElement.scrollTop,{left:r.left+cI().documentElement.scrollLeft+n.offsetWidth/2,top:i+n.offsetHeight/2}),c=o-a.left,u=s-a.top,l=Math.abs((c+u)/50).toFixed(0),p=l>0?l:1;return Gv.Observable.interval(e.moveFrequency).timeInterval().map((function(e){return{cursorInitialPosLeft:o,cursorInitialPosTop:s,cursorDistanceDiffLeft:c,cursorDistanceDiffTop:u,totalCircleSteps:l,interval:e}})).do(e.moveCursorToPosition(t.cursor)).skip(p-1).take(1).mapTo(t)}},vI=function(e){return e||(e={moveCursorCirclePosition:dI,circleFrequency:50}),function(t){return Gv.Observable.interval(e.circleFrequency).timeInterval().do((function(n){return e.moveCursorCirclePosition(t.cursor,n.value)})).skip(107).take(1).mapTo(t)}},mI=function(e,t){e.style.opacity=t>=1?1:(parseFloat(t)+.1).toFixed(1)},yI=function(e,t){t<=.1?(e.style.opacity=0,e.style.display="none"):e.style.opacity=(parseFloat(t)-.1).toFixed(1)},gI=function(e,t,n){return Gv.Observable.interval(t.stepDuration).do((function(){var r=e.cursor.style.opacity;"in"===n&&t.fadeInStep(e.cursor,r),"out"===n&&t.fadeOutStep(e.cursor,r)})).skip(9).take(1).mapTo(e)},_I=function(e){return e||(e={fadeInStep:mI,stepDuration:20}),function(t){return gI(t,e,"in")}},wI=function(e){return e||(e={fadeOutStep:yI,stepDuration:120}),function(t){return gI(t,e,"out")}},EI=new(function(){function e(t){s(this,e),this.key=t;var n=localStorage.getItem(this.key);this.items=n?JSON.parse(n):[]}return c(e,[{key:"asArray",value:function(){return this.items}},{key:"add",value:function(e){return this.items.push(e),this._persist()}},{key:"top",value:function(){return this.items[0]||null}},{key:"purge",value:function(){var e=JSON.parse(localStorage.getItem(this.key));this.includesItems(e)&&(localStorage.removeItem(this.key),this.items=[])}},{key:"includesItems",value:function(e){return Array.isArray(e)&&e.length}},{key:"removeTop",value:function(){return this.items.shift(),this._persist()}},{key:"_persist",value:function(){return localStorage.setItem(this.key,JSON.stringify(this.items))}}]),e}())("custom_commands"),OI=function(e){return e?(EI.add(e),[e]):EI.asArray()},SI=function(){return EI.removeTop()},TI=function(e){var t=e.targetElement;SI(),t.click()},kI="virtual_assistant_cobrowsing",xI="point",AI="scroll",II="click",NI="navigate",CI=[AI,xI,II],RI=[II],PI=function(e){return e.targetElement.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})},MI=function(e,t){e.operatorName;var n=e.operatorFormattedName;return function(e){var t,r,i=e.properties[kI];if(t=i.target,!((r=i.type)===NI?t&&t.length:k.contains(r,CI)?Boolean(uI(t)):(nm.info("Invalid Virtual Assistant Cobrowsing action type",{type:r}),0)))return Gv.Observable.of(e);switch(i.type){case xI:return fI(0,n).map(k.assoc("targetElement",uI(i.target))).do(PI).flatMap(_I()).flatMap(bI()).flatMap(vI()).flatMap(wI()).mapTo(e);case II:return fI(0,n).map(k.assoc("targetElement",uI(i.target))).do(PI).flatMap(_I()).flatMap(bI()).flatMap(vI()).do(TI).flatMap(wI()).mapTo(e);case AI:return fI(0,n).map(k.assoc("targetElement",uI(i.target))).do(PI).flatMap(_I()).flatMap(bI()).mapTo(e);case NI:return function(e){return aI()?document.getElementById("inner-page").contentWindow.location.assign(e):window.location.href=e,Gv.Observable.of({})}(i.target).mapTo(e);default:throw new Error("Unknown action: ".concat(i.type))}}},jI="custom_command",LI=function(e){return k.has(kI,e.properties)},qI=function e(t){var n=this,r=t.media,i=t.medias,o=t.onAccept,a=t.onDecline,c=t.validateMedia;s(this,e),this.media=r,this.medias=i,c=c||PA;this.select=function(e,t){return c({options:t,availableMediaTypes:n.medias,availableOneWayMediaTypes:[],media:e}).then((function(){return function(e,t){return o({media:e,options:t})}(e,t)}))},this.decline=a},UI=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),DI=function(e){var t=e.visitorId,r=e.engagementId,i=e.volatileNotifications,o=e.engagementStateObservable,s=e.wsProxy,a=e.apiTimeoutMilliseconds,c=e.stats,u=Ig({stats:c,protocol:"rest",failureTagProperty:"message",timeout:a,timeoutError:Gv.Observable.throw(UI)});return{mediaUpgradeRequestObservable:function(e,t){var n=k.propEq("event_type","engagement.media_upgrade_request"),r=k.pathEq(["media_upgrade_request","engagement_id"],e),i=k.pathEq(["media_upgrade_request","target"],"visitor"),o=k.compose(k.pick(["id","audio","video"]),k.prop("media_upgrade_request"));return t.filter(k.allPass([n,r,i])).map(o)}(r,i),mediaStateObservable:function(e){return e.filter(k.identity).map(k.prop("media")).distinctUntilChanged(k.equals)}(o),requestMediaUpgrade:function(e){var t=e.mediaUpgradeRequest;return u({resource:"media-upgrade-request",method:"create"},(function(){return s.request({method:"POST",url:"".concat(n.default.api_url,"/engagements/").concat(r,"/media_upgrade_requests"),payload:t,headers:ig}).catch((function(e){return pg(e,{allowedCauses:[Ky.SALEMOVE.INVALID_INPUT,Ky.SALEMOVE.NETWORK_TIMEOUT,Ky.SALEMOVE.CONFLICT]})}))})).toPromise()},acceptUpgradeRequest:function(e,t){return u({resource:"media-upgrade-request",method:"accept"},(function(){return s.request({method:"PATCH",url:"".concat(n.default.api_url,"/engagements/").concat(r,"/media_upgrade_requests/").concat(e.id),payload:k.merge(t,{action:"accept"}),headers:ig}).catch((function(e){return pg(e,{allowedCauses:[Ky.SALEMOVE.INVALID_INPUT,Ky.SALEMOVE.NETWORK_TIMEOUT,Ky.SALEMOVE.CONFLICT]})}))})).toPromise()},declineUpgradeRequest:function(e){return u({resource:"media-upgrade-request",method:"decline"},(function(){return s.request({method:"PATCH",url:"".concat(n.default.api_url,"/engagements/").concat(r,"/media_upgrade_requests/").concat(e.id),payload:{action:"decline"},headers:ig}).catch((function(e){return pg(e,{allowedCauses:[Ky.SALEMOVE.INVALID_INPUT,Ky.SALEMOVE.NETWORK_TIMEOUT,Ky.SALEMOVE.CONFLICT]})}))})).toPromise()},removeVideo:function(){return u({resource:"engagement-participant",method:"remove video"},(function(){return s.request({method:"PATCH",url:"".concat(n.default.api_url,"/engagements/").concat(r,"/participants/").concat(t),payload:{action:"remove_video"},headers:ig}).catch(pg)})).map((function(){return{}})).toPromise()},removeAudio:function(){return u({resource:"engagement-participant",method:"remove audio"},(function(){return s.request({method:"PATCH",url:"".concat(n.default.api_url,"/engagements/").concat(r,"/participants/").concat(t),payload:{action:"remove_audio"},headers:ig}).catch(pg)})).map((function(){return{}})).toPromise()}}},VI=function(e){return/android/i.test(e.userAgent)},FI=Object.freeze({__proto__:null,screenCapturingSupported:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.navigator;return Boolean(k.path(["mediaDevices","getDisplayMedia"],e))&&!VI(e)}}),BI=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:yk,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:FI,n=e.canReceiveMedia()?["browser"]:[],r=e.canSendMedia()?["browser"]:[];return{canReceive:{video:n,audio:n.concat(["phone"])},canSend:{video:r,audio:r.concat(["phone"])},canShareScreen:t.screenCapturingSupported()&&e.canSendMedia()}},HI=function(e,t){return t.filter(wA).map((function(t){var n=t.upgradeRequest,r=t.currentMediaState,i=function(e,t){if("two_way"===e.video)return{media:"video",medias:["video"]};if("two_way"===e.audio)return{media:"audio",medias:t.canSend.audio.map(_A)};throw new Error("Tried to create upgrade offer for one way media")}(n,BI());return new qI(k.merge(i,{onAccept:function(t){return e.acceptUpgradeRequest(n,function(e,t){var n=(e.options?e.options.phoneNumber:void 0)||k.path(["audio","phone_number"],t),r=(e.options?e.options.phoneExtension:void 0)||k.path(["audio","phone_extension"],t);return{audio_type:"video"===e.media?k.path(["audio","type"],t)||"browser":"phone"===e.media?"phone":"browser",phone_number:n,phone_extension:r}}(t,r)).then(k.always({}))},onDecline:function(){return e.declineUpgradeRequest(n).then(k.always({}))}}))})).share()},WI=function(e){var t,n=e.commsApi||DI(k.pick(["engagementId","visitorId","volatileNotifications","engagementStateObservable","wsProxy","apiTimeoutMilliseconds","stats"],e)),r=new Gv.Subscription,i=n.mediaUpgradeRequestObservable.switchMap((t=e.channelObservable,function(e){return t.take(1).do((function(t){return t.channel.emit("comms:media_upgrade_request:ack",{id:e.id})})).mapTo(e)})).withLatestFrom(n.mediaStateObservable).map(k.zipObj(["upgradeRequest","currentMediaState"])).share();r.add(function(e,t){return t.filter(k.complement(wA)).do((function(e){var t=e.upgradeRequest;return nm.info("Accepting media request automatically",{upgrade_request:t})})).switchMap((function(t){var n=t.upgradeRequest,r=t.currentMediaState;return e.acceptUpgradeRequest(n,{audio_type:k.path(["audio","type"],r),phone_number:k.path(["audio","phone_number"],r),phone_extension:k.path(["audio","phone_extension"],r)})})).catch((function(){return Gv.Observable.empty()})).subscribe((function(){}))}(n,i));return r.add(bm.vent.observable(bm.MSG.ENGAGEMENT_REMOVE_AUDIO).subscribe(n.removeAudio,nm.error.bind(nm,"Error removing visitor's audio"))),{removeVideo:n.removeVideo.bind(n),mediaUpgradeOffers:HI(n,i),mediaStateObservable:n.mediaStateObservable,requestMediaUpgrade:function(e){return n.mediaStateObservable.take(1).switchMap((function(t){var r=function(e){var t=e.options,n=e.currentMediaState,r=k.path(["audio","direction"],n),i=k.path(["video","direction"],n),o=t.audio?EA:null,s=t.video?t.video:null,a=SA(o,r),c=SA(s,i),u=k.path(["audio","phone_number"],n)||t.phoneNumber||null,l=k.path(["audio","phone_extension"],n)||t.phoneExtension||null;return{audio:a,video:c,audio_type:k.path(["audio","type"],n)||t.audio||null,phone_number:u,phone_extension:l}}({options:e,currentMediaState:t});return n.requestMediaUpgrade({mediaUpgradeRequest:r})})).toPromise().then(k.always({}))},stop:function(){r.unsubscribe()}}},GI=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),zI=function(e){return e instanceof DOMException?ug(e):e instanceof ag?e:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(0===e)return new ag({cause:Ky.SALEMOVE.CONNECTION_LOST});var o=k.equals(e,404)?Ky.SALEMOVE.RESOURCE_NOT_FOUND:k.contains(e,eg)?Ky.SALEMOVE.INVALID_INPUT:k.equals(e,429)?Ky.SALEMOVE.TOO_MANY_REQUESTS:401===e||403===e?Ky.SALEMOVE.FORBIDDEN:(nm.warn("An INTERNAL_ERROR error from XHR occurred. Can we expose this error as non-internal?",i({status:e,message:n,responseText:t},r)),Ky.SALEMOVE.INTERNAL_ERROR),s=function(){try{return JSON.parse(t).message}catch(e){}};return n||(n=t?s():void 0),new ag(n?{cause:o,message:n}:{cause:o})}(e.status,e.response&&e.response.text&&e.response.text(),e.response?e.response.message:void 0,e)},JI=function(){function e(t,n){var r=this,i=t.id,o=t.securityScanningRequired,a=t.url;if(s(this,e),this.id=i,this.securityScanningRequired=o,this.url=a,this.securityScanningRequired){var c=k.pathEq(["security_scan_result","file_id"],this.id);this.scanResultObservable=n.find(c).map(k.path(["security_scan_result","result"])).map((function(e){return{result:e,file:r}}))}}return c(e,[{key:"getScanResult",value:function(){return this.securityScanningRequired?this.scanResultObservable.toPromise():Promise.reject("Security scanning is not required")}}]),e}(),QI=function(e,t,n,r,i){var o=n.onUploadProgress,s=n.getRequestHeaders,a=new FormData;a.append("content",t),a.append("site_id",sm.siteId);var c=xx(e?"/engagements/".concat(e,"/files"):"/messaging/files");return k.contains(t.type,i)?t.size>25e6?Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.FILE_TOO_LARGE,message:"File exceeds the maximum file size"})):function(e){var t=e.method,n=e.url,r=e.payload,i=e.onUploadProgress,o=e.getRequestHeaders;return qg({method:t,url:n,payload:r,responseType:"json",onUploadProgress:i,getRequestHeaders:o})}({url:c,method:"POST",payload:a,getRequestHeaders:s,onUploadProgress:o}).map((function(e){var t=e.response;return new JI({id:t.file_id,securityScanningRequired:t.security_scanning_required,url:c},r)})).catch((function(e){return Gv.Observable.throw(zI(e))})):Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.FILE_CONTENT_TYPE_NOT_ALLOWED,message:"File content type is not allowed"}))},YI=function(){function e(t){var n=t.iframe;s(this,e),this.iframe=n}return c(e,[{key:"deframe",value:function(){bm.vent.trigger("visit:restore_url")}}]),e}(),KI=function e(t){var n=t.unwrap;s(this,e),this.unwrap=n},XI=function e(){s(this,e),this.responsePromise=Gv.Observable.merge(bm.vent.observable(bm.MSG.ALLOW_STREAM).map(k.always("allowed")),bm.vent.observable(bm.MSG.DENY_STREAM).map(k.always("denied"))).take(1).toPromise()},$I=function e(t){var n=t.status,r=t.authenticated;s(this,e),this.status=n,this.authenticated=r};$I.prototype.STATUSES={ENGAGED:"engaged",TRANSFERRING:"transferring"};var ZI=function e(t){var n=t.text;s(this,e),this.text=n},eN=function(){function e(t){var n=this;s(this,e),this.startSalemoveViews=this.startSalemoveViews.bind(this);var r=t.engagementId,i=t.subEngagementId,o=t.startingMedia,a=t.type,c=t.isReestablishing,u=t.chat,l=t.stopChat,p=t.webRtcMode,f=t.enabledMediaLevel,h=t.channelObservable,d=t.operator,b=t.operatorFocusObservable,v=t.communicationWidget,m=t.createEngagementObservable,y=t.mediaStateObservable,g=t.backend,_=t.platform,w=t.startScreenSharing,E=t.stateObservable,O=t.statsClient,S=t.entrypoint,T=t.volatileNotifications,x=t.statusObservable,A=t.comms,I=t.events,N=t.surveyApi,C=t.getRequestHeaders,R=t.siteVisitorNotifications,P=t.createdAt,M=t.cobrowser;this.engagementId=r,this.chat=u,this.mediaState=null,this.isReestablishing=c,this.createdAt=P,this.subEngagementId=i,this.startingMedia=o,this.type=a,this.operator=d,this.cobrowser=M,this.allowFileSending=sm.conf.communications.allow_file_sending,this.allowedFileContentTypes=sm.conf.communications.allowed_file_content_types;var j=w({conf:sm.conf,channelObservable:h,isReestablishing:this.isReestablishing,stats:O}),L=j.screenSharing,q=j.stopScreenSharing;this.screenSharing=L;var U=new Gv.Subscription,D=t.engagementEndObservable.map(k.always({})).take(1);y=y.publishReplay(1).refCount(),b=b.map((function(e){return"chat"===e?n.FOCUS_TARGETS.CHAT:"cobrowse"===e?n.FOCUS_TARGETS.COBROWSER:(nm.error("Unexpected focus target!",e),"")}));var V=bm.vent.observable(bm.MSG.PUBLIC.ENGAGEMENT_MEDIA_UPGRADE_REQUEST).map(k.construct(YA)),F=bm.vent.observable(bm.MSG.WILL_ASK_MEDIA_PERMISSION).map(k.construct(XI)),B=function(e){return e.filter(k.propEq("event",jI)).map((function(e){var t=e.payload,n=e.custom_command_id;return k.construct(sI)({properties:t,id:n})})).filter((function(e){return k.not(LI(e))})).distinct(k.prop("id")).do((function(e){return nm.info("Custom Command: received",{custom_command_id:e.id})}))}(T),H=function(e){return e.filter(k.propEq("event",jI)).map((function(e){var t=e.payload,n=e.custom_command_id;return k.construct(sI)({properties:t,id:n})})).filter((function(e){return LI(e)})).distinct(k.prop("id")).do((function(e){return nm.info("Virtual CoBrowsing Command: received",{custom_command_id:e.id})})).startWith(null).flatMap((function(e){var t=OI(e);return Gv.Observable.from(t)})).do((function(e){return nm.info("Virtual CoBrowsing Command: processing",{custom_command_id:e.id})}))}(T).concatMap(MI({operatorName:d.name,operatorFormattedName:d.formattedName})).do((function(e){(function(e){var t=e.properties[kI].type;return!k.contains(t,RI)})(e)&&SI()})).subscribe((function(){}),nm.error),W=Qg(),G=E.distinctUntilChanged(k.equals,(function(e){return e.capabilities})).map((function(e){return new ZI(e.capabilities)})),z=k.fromPairs([[this.EVENTS.END,D],[this.EVENTS.STATE_CHANGE,E.map((function(e){var t=e.status,n=e.visitor;return{status:t,authenticated:k.propOr(!1,"authenticated")(n)}})).map(k.construct($I))],[this.EVENTS.CAPABILITIES,G],[this.EVENTS.MEDIA_UPGRADE_OFFER,A.mediaUpgradeOffers],[this.EVENTS.FOCUS,b],[this.EVENTS.MEDIA_STATE_CHANGE,y],[this.EVENTS.MEDIA_PERMISSION_REQUEST,F],[this.EVENTS.WIDGET_MEDIA_UPGRADE_REQUEST,V],[this.EVENTS.CUSTOM_COMMAND,B]]);W.proxyAll(z),this.addEventListener=function(e,t){e===this.EVENTS.COBROWSING_REQUEST?this.cobrowser.addUnbufferedEventListener(gA.prototype.EVENTS.COBROWSING_REQUEST,t):W.addEventListener(e,t)},this.removeEventListener=function(e,t){e===this.EVENTS.COBROWSING_REQUEST?this.cobrowser.removeUnbufferedEventListener(gA.prototype.EVENTS.COBROWSING_REQUEST,t):W.removeEventListener(e,t)},this.recordEvent=function(e){return I.recordEvent(e)};var J=k.propEq("event_type","engagement.files.security_scan_result"),Q=R.filter(J).publishReplay(this.SCAN_EVENT_REPLAY_COUNT);U.add(Q.connect()),this.uploadFile=function(e,t){t||(t={});var n=t.onUploadProgress;return QI(this.engagementId,e,{onUploadProgress:n,getRequestHeaders:C},Q,this.allowedFileContentTypes).toPromise()},this.getChatTranscript=function(){return g.chatTranscript().then((function(e){return Promise.resolve(k.map((function(e){var t=e.id,n=e.message,r=e.sender,i=e.attachment,o=e.metadata,s=e.created_at,a=r.type;return"operator"===a?new Lx({id:t,content:n,attachment:i,metadata:o,created_at:s,sender:r}):"visitor"===a?new jx({id:t,content:n,status:jx.prototype.STATUSES.DELIVERED,attachment:i,created_at:s}):null}),e))}))},this.observable=function(e){return e===this.EVENTS.COBROWSING_REQUEST?this.cobrowser.observable(gA.prototype.EVENTS.COBROWSING_REQUEST):W.observable(e)};var Y=function(){return setTimeout((function(){return W.stop()}))};D.subscribe((function(){}),Y,Y),this.iframePage=function(e){e||(e={});var t=e.keptElementSelectors;nm.info("Engagement: Iframe page started");var n=new zA({id:"inner-page",getTargetUrl:function(){return window.location.href},document:window.document,nonRemoved:t||[]});return sm.visitorPageNotifierSubscription&&sm.visitorPageNotifierSubscription.unsubscribe(),sm.trackerSubscription.unsubscribe(),sm.cobraSubscription.unsubscribe(),n.putIntoIframe().then((function(e){var t=e.iframe;return nm.info("Engagement: Iframe page finished"),Promise.resolve(new YI({iframe:t}))}))},this.wrapPage=function(e){e||(e={});var t=e.keptElementSelectors;nm.info("Engagement: Wrap page started");var n=new QA({document:window.document,nonRemoved:t||[]});return n.wrap(),nm.info("Engagement: Wrap page finished"),Promise.resolve(new KI({unwrap:n.unwrap}))};var K=kA({stateObservable:E}).share();U.add(XA({volatileNotifications:T,visitorPageAdaption:sm.conf.visitor_app.visitor_page_adaption})),this.getSurvey=function(){return N.fetchSurvey()};var X=W.eventWithoutListenerObservable(this.EVENTS.WIDGET_MEDIA_UPGRADE_REQUEST);U.add(X.subscribe((function(){console.warn("No listener set for the Engagement WIDGET_MEDIA_UPGRADE_REQUEST event. See 'WidgetMediaUpgradeRequest' documentation for how to add the listener to enable media upgrades from the sm-engaged-visitor widget."),nm.warn("Listener is not set for WIDGET_MEDIA_UPGRADE_REQUEST")}),nm.error));U.add(y.subscribe((function(e){n.mediaState=e}),nm.error));var $=m({engagement:this,transfers:K,channelObservable:h,webRtcMode:p,statusObservable:x});v.start($),this.communicationWidget=v;var Z=function(){return v.stop(),A.stop(),l(),q(),function(e){var t=e.cursorIdentifier,n=e.onRemove;if(!aI()){var r=uI(t||"#"+lI);if(r&&(cI().body.removeChild(r),n))n()}}({}),nm.info("Triggering ENGAGEMENT_END event"),bm.vent.trigger(bm.MSG.PUBLIC.ENGAGEMENT_END,n),U.unsubscribe()};this.start=function(){var e;n.isReestablishing||(e=["action:reach","stage:establish-engagement"],O.increment("engagement.flow",["entrypoint:".concat(S)].concat(e)));var t,r=bm.vent.trigger.bind(bm.vent,bm.MSG.ENGAGEMENT_TRANSFERRED);n.isReestablishing||EI.purge(),t={engagementObservable:$},bm.reqres.setHandler("get:engagement_observables",k.always(t)),U.add(K.subscribe((function(e){return function(e){n.operator=jk({id:e.operatorId,name:e.operatorName,formattedName:e.operatorFormattedName,picture:{url:e.operatorPicture},mediaType:e.operatorMedia,webRtcMode:p,enabledMediaType:f})}(e),r(e)}),nm.error)),U.add(D.subscribe(Z,nm.error)),bm.vent.trigger(bm.MSG.PUBLIC.ENGAGEMENT_START,n)},this.upgrade=function(e){if(_===rg)return Promise.reject(new ag({cause:Ky.SALEMOVE.NOT_SUPPORTED,message:"Unsupported functionality for OmniBrowse engagement"}));var t=n.operator.state.media,r=n.operator.state.oneWayMedias,i=sm.conf.communications.allow_upgrade_requests,o=n.mediaState.operator.media,s="phone"===o?"audio":o;return nm.info("Initiating media upgrade",{audio_type:e.audio,video_type:e.video,caller:(e?e.caller:void 0)||"client_integrator"}),MA({options:e,availableMediaTypes:t,availableOneWayMediaTypes:r,visitorUpgradesAllowed:i,highestAllowedMediaType:s}).then((function(){return A.requestMediaUpgrade(e)}))},this.end=function(){return Z(),g.end().then(k.always({})).catch((function(e){return 422===(e?e.status:void 0)?(nm.warn("Engagement already ended",{error:e,engagement_id:n.engagementId}),Promise.reject(new ag({cause:Ky.SALEMOVE.CONFLICT}))):k.isNil(e.status)?(nm.warn("Engagement end failed. No connection",{error:e,engagement_id:n.engagementId}),Promise.reject(new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}))):e.status>500&&e.status<=504?(nm.warn("Engagement end failed. Service unavailable",{error:e,engagement_id:n.engagementId}),Promise.reject(new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}))):(nm.error("Engagement end failed",{error:e,engagement_id:n.engagementId}),Promise.reject(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR})))}))};var ee=new Gv.Subject;this.notifyOfFocusChange=function(e){return ee.next(e)};var te=ee.asObservable().distinctUntilChanged().withLatestFrom(h,(function(e,t){return{target:e,channel:t.channel}})).subscribe((function(e){var t=e.target;return e.channel.emitAll("visitor:focus_changed",t)}),nm.error);U.add(te),U.add(H)}return c(e,[{key:"start",value:function(){}},{key:"upgrade",value:function(e){return null}},{key:"iframePage",value:function(e){return null}},{key:"wrapPage",value:function(e){}},{key:"getSurvey",value:function(){return null}},{key:"end",value:function(){return null}},{key:"notifyOfFocusChange",value:function(){return null}},{key:"startSalemoveViews",value:function(){nm.error("Private/undocumented Engagement#startSalemoveViews was used"),console.error("Usage of Engagement#startSalemoveViews is not supported")}},{key:"addEventListener",value:function(e,t){}},{key:"removeEventListener",value:function(e,t){}},{key:"recordEvent",value:function(e){return null}},{key:"uploadFile",value:function(e,t){return null}},{key:"getChatTranscript",value:function(){return null}}],[{key:"create",value:function(t){var n=t.engagementId,r=t.subEngagementId,i=t.startingMedia,o=t.mediaState,s=t.type,a=t.isReestablishing,c=t.initialChatHistoryObservable,u=t.operator,l=t.statsClient,p=t.cobra,f=t.channelObservable,h=t.platform,d=t.engagementApi,b=t.connectionStatusObservable,v=t.getRequestHeaders,m=t.internalVisitorStateObservable,y=t.entrypoint,g=t.volatileNotifications,_=t.statusObservable,w=t.pubsub,E=t.wsProxy,O=t.createdAt,S=m.map(k.compose(k.find(k.propEq("id",n)),k.pathOr([],["engagement","engagements"]))),T=S.filter(k.identity).take(1),x=T.flatMap((function(){return S.filter(k.complement(k.identity)).take(1)})),A=bm.vent.observable("engagement:disengage"),I=Gv.Observable.merge(x,A).take(1),N=f.switchMap((function(e){return e.channel.observable("visitor:state_changed")})),C=T.map(k.prop("transferrable_sites")),R=Jv(),P=C.flatMap((function(e){var t=e.map((function(e){return e.id}));return w.joinSiteVisitorNotifications(R,t)})),M=sm.conf.engagement.api_timeout_milliseconds||Xy,j=WI({visitorId:Jv(),engagementId:n,volatileNotifications:g,engagementStateObservable:S,apiTimeoutMilliseconds:M,wsProxy:E,stats:l,channelObservable:f});nm.info("Starting medra communication controller");var L=bm.request("comms:create_controller",{requestHeaders:v(),visitorAppConf:sm.conf.visitor_app,statsClient:l,volatileNotifications:g,comms:j,pubsub:w,localCapabilities:BI(),onMediaUpgrade:function(e){return d.createMediaUpgrade(e).subscribe(nm.log.bind(nm,"Media upgrade successfully created"),nm.warn.bind(nm,"Failed to create media upgrade"))}}),q=function(e){var t=e.mediaState,n=e.mediaStateChanges,r=t?Gv.Observable.of(t):Gv.Observable.of(new jA({visitor:{media:"text",audioMuted:!1,videoMuted:!1},operator:{media:"text",audioMuted:!1,videoMuted:!1}}));return n.merge(r).map(k.construct(jA))}({mediaState:o,mediaStateChanges:L.mediaStateChanges()}),U=Gv.Observable.merge(c,Nx({engagementId:n,connectionStatusObservable:b})),D=sm.conf.masking_regular_expressions;D||(nm.error("Failed to fetch masking_regular_expressions for site",{site_id:sm.siteId,visitor_id:Jv()}),D=[]);var V=dA.create({chatHistoryObservable:U,engagementEndObservable:I,engagementId:n,statsClient:l,getRequestHeaders:v,siteVisitorNotifications:P,maskingRegularExpressions:D}),F=V.chat,B=V.stopChat,H={end:function(){return d.endEngagement({engagementId:n}).toPromise()},chatTranscript:function(){return d.getChatTranscript(n).map(k.filter((function(e){var t=e.sender.type;return k.contains(t,["operator","visitor"])}))).toPromise()}},W=Ek(),G=sm.conf.communications.enabled_media_level,z=function(e){var t=e.engagementId,n=e.wsProxy,r=e.apiTimeoutMilliseconds,i=e.stats,o=Ig({stats:i,protocol:"rest",failureTagProperty:"message",timeout:r,timeoutError:Gv.Observable.throw(GI)});return{recordEvent:function(e){return o({resource:"record-event",method:"create"},(function(){return n.request({method:"POST",url:"".concat(sm.conf.api_url,"/engagements/").concat(t,"/events"),payload:e,headers:ig}).catch(pg,{allowedCauses:[Ky.SALEMOVE.INVALID_INPUT,Ky.SALEMOVE.NETWORK_TIMEOUT]})})).toPromise()}}}({engagementId:n,wsProxy:E,apiTimeoutMilliseconds:M,stats:l}),J=function(e){var t=e.engagementId,n=e.wsProxy,r=e.apiTimeoutMilliseconds,i=e.stats,o=Ig({stats:i,protocol:"rest",failureTagProperty:"message",timeout:r,timeoutError:Gv.Observable.throw(DA)}),s=function(e){switch(e.status){case 409:return nm.warn("Survey was not accepted because at least some answers were not unique for engagement. This could happen when survey was answered twice for the same engagement.",{engagement_id:t}),Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.CONFLICT}));default:return pg(e)}},a=function(e){var r=e.surveyId,i=e.answers;return o({resource:"survey-answers-post",method:"create"},(function(){return n.request({method:"POST",url:"".concat(sm.conf.api_url,"/surveys/").concat(r,"/answers"),payload:{engagement_id:t,answers:i},headers:ig}).catch(s)})).toPromise()};return{fetchSurvey:function(){return o({resource:"survey-request",method:"get"},(function(){return n.request({method:"GET",url:"".concat(sm.conf.api_url,"/engagements/").concat(t,"/survey"),payload:null,headers:ig}).catch(pg)})).map((function(e){return new UA(e,a)})).toPromise()},saveSurveyAnswers:a}}({engagementId:n,wsProxy:E,apiTimeoutMilliseconds:M,stats:l}),Q=new gA({cobra:p,operator:u,channelObservable:f});return i&&(u=function(e,t){var n=e.media,r=e.enabledMediaType,i=e.webRtcMode;if(k.indexOf(n,t.state.medias)>-1)return t;var o=Sk[n];return k.compose(Ck({enabledMediaType:r,webRtcMode:i}),k.set(kk,o),k.set(Tk,o))(t)}({media:i,enabledMediaType:G,webRtcMode:W},u)),new e({engagementId:n,subEngagementId:r,engagementEndObservable:I,startingMedia:i,type:s,isReestablishing:a,chatHistoryObservable:U,chat:F,stopChat:B,webRtcMode:W,enabledMediaLevel:G,channelObservable:f,operator:u,operatorFocusObservable:N,communicationWidget:L,createEngagementObservable:xA,mediaStateObservable:q,cobra:p,backend:H,platform:h,startScreenSharing:oI.start,stateObservable:S.filter(k.identity).distinctUntilChanged(k.equals),statsClient:l,entrypoint:y,volatileNotifications:g,statusObservable:_,comms:j,events:z,surveyApi:J,getRequestHeaders:v,siteVisitorNotifications:P,createdAt:O,cobrowser:Q})}}]),e}();eN.prototype.SCAN_EVENT_REPLAY_COUNT=100,eN.prototype.EVENTS={END:"end",STATE_CHANGE:"state_change",CAPABILITIES:"capabilities",MEDIA_UPGRADE_OFFER:"media_upgrade_offer",FOCUS:"focus",MEDIA_STATE_CHANGE:"media_state_change",COBROWSING_REQUEST:"cobrowsing_request",MEDIA_PERMISSION_REQUEST:"media_permission_request",WIDGET_MEDIA_UPGRADE_REQUEST:"widget_media_upgrade_request",CUSTOM_COMMAND:"custom_command"},eN.prototype.FOCUS_TARGETS={CHAT:"chat",COBROWSER:"cobrowse"},eN.prototype.MEDIA_TYPES={TEXT:"text",AUDIO:"audio",PHONE:"phone",VIDEO:"video"};var tN=function(e){var t,n,r=e.api,i=e.conf,o=e.operatorsObservable,s=e.media,a=e.options,c=e.statsClient,u=e.cobraObservable,l=e.channelObservable,p=e.engagementApi,f=e.webRtcMode,h=e.enabledMediaLevel,d=e.connectionStatusObservable,b=e.getRequestHeaders,v=e.internalVisitorStateObservable,m=e.volatileNotifications,y=e.statusObservable,g=e.pubsub,_=e.wsProxy,w=e.dynamicImport,E=new Gv.AsyncSubject,O=Mx({media:s,mediaOptions:a,mediaValidation:PA,api:r,notifyOfTimeout:bm.vent.trigger.bind(bm.vent,bm.MSG.REACTIVE_ENGAGEMENT_REQUEST_TIMEOUT),operatorsObservable:o,engagementCoreObservable:w("Comms"),cobraObservable:u,channelObservable:l,serverResponseTimeout:Xy,communicationLib:i.communications.lib,engagementApi:p,webRtcMode:f,enabledMediaLevel:h,statsClient:c}),S=O.requestObservable,T=O.resultObservable,x=ty(E),A=T.merge(x).take(1).map((function(e){return k.merge(e,{statsClient:c,connectionStatusObservable:d,getRequestHeaders:b,internalVisitorStateObservable:v,volatileNotifications:m,statusObservable:y,pubsub:g,wsProxy:_})})).map(eN.create).do(k.invoker(0,"start")).catch(lg);return{operatorObservable:(t=S,n=x,t.map(k.prop("operator")).merge(n).take(1)).catch(lg),engagementObservable:A,cancelEngagementRequest:function(){return function(e){var t=e.api,n=e.requestObservable,r=e.resultErrorSubject,i=e.statsClient;return n.catch((function(){return Gv.Observable.of({requestNotCreated:!0})})).flatMap((function(e){var n=e.engagementRequestId;return e.requestNotCreated?Gv.Observable.of({}):t.cancel({id:n}).do((function(){return r.next(new ag({cause:Ky.SALEMOVE.CANCEL}))})).do((function(){return i.increment("engagement.flow",["entrypoint:reactive-request","action:end","stage:requested","expected:true","reason:cancel"])}))}))}({statsClient:c,api:r,requestObservable:S,resultErrorSubject:E}).toPromise()},engagementRequestTimeout:1e3*i.engagement.reactive_call_timeout}},nN=function e(t){var n=t.timeout,r=t.engagementPromise,i=t.cancel,o=t.operatorPromise;s(this,e),this.timeout=n,this.engagementPromise=r,this.cancel=i,this.operatorPromise=o},rN=function(e){l(n,e);var t=m(n);function n(){var e;return s(this,n),(e=t.call(this))._currentSubscription=se.EMPTY,e}return c(n,[{key:"add",value:function(e){if(!this.closed)return"function"==typeof e&&(e=new se(e)),this._currentSubscription&&(this.remove(this._currentSubscription),this._currentSubscription.unsubscribe(),this._currentSubscription=null),y(p(n.prototype),"add",this).call(this,this._currentSubscription=e),this}}]),n}(se),iN=function e(t,n){s(this,e),this.code=t,this.validDuration=n},oN=function(){function e(t){s(this,e);var n=t.incomingEngagementRequestObservable,r=t.setOmnibrowseReestablishHandler,i=t.statsClient,o=t.wsProxy,a=new rN,c=n.filter(k.propEq("platform",rg)).map(k.prop("incomingEngagementRequest"));this.setIncomingEngagementRequestHandler=function(e){return a.add(c.subscribe(e,nm.error))},this.setEngagementReestablishHandler=r,this.getVisitorCode=function(){return Ig({stats:i,protocol:"rest",failureTagProperty:"error",timeout:Xy,timeoutError:Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}))})({resource:"omnibrowse",method:"get"},(function(){return o.request({method:"GET",url:"".concat(sm.conf.api_url,"/omnibrowse/sites/").concat(Xv(),"/visitor_code/").concat(Jv()),payload:null,headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json"}})})).map((function(e){var t=Date.parse(e.expires_at)-new Date;return new iN(e.code,t)})).catch(k.compose(Gv.Observable.throw,k.unless(k.is(ag),k.always(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR}))))).do(null,(function(e){return nm.warn("Fetching visitor code failed",{site_id:sm.siteId,err:e})})).toPromise()}}return c(e,[{key:"setIncomingEngagementRequestHandler",value:function(e){}},{key:"setEngagementReestablishHandler",value:function(e){}},{key:"getVisitorCode",value:function(){return null}}]),e}(),sN=function e(t){var n=t.text,r=t.noOperatorsOnlineText,i=t.duration,o=t.priority;s(this,e),this.text=n,this.noOperatorsOnlineText=r,this.duration=i,this.priority=o},aN=function e(t){s(this,e),this.duration=t},cN=function e(t){var n=t.verticalOffset,r=t.horizontalOffset;s(this,e),this.verticalOffset=n,this.horizontalOffset=r},uN=function e(t){s(this,e),this.text=t},lN=function e(t,n){s(this,e),this.text=t,this.duration=n},pN=function e(t){var n=t.operatorListReady,r=t.isOmniqEnabled,i=t.queueStateReady,o=t.routingObservable;s(this,e);var a=function(e){return r?e.flatMap((function(e){return Gv.Observable.combineLatest(o,i).take(1).mapTo(e)})):e.flatMap((function(e){return n.mapTo(e)}))},c=bm.vent.observable("reactive_bar:enable").map(k.always({})),u=bm.vent.observable("reactive_bar:disable").map(k.always({})),l=bm.vent.observable("reactive_bar:set_position").map((function(e){return new cN(e)})),p=bm.vent.observable("trigger_expand_reactive").map((function(e){return new aN(e.duration)})),f=bm.vent.observable("trigger_media_selection").map((function(e){return new uN(e.text)})),h=bm.vent.observable("trigger_reactive_callout").map((function(e){return new sN({text:e.text,noOperatorsOnlineText:e.noOperatorsOnlineText,duration:e.duration,priority:e.priority})})),d=bm.vent.observable("show_engagement_invitation").map((function(e){return new lN(e.text,e.duration)})),b=k.fromPairs([[this.EVENTS.REACTIVE_ENABLE,c],[this.EVENTS.REACTIVE_DISABLE,u],[this.EVENTS.REACTIVE_SET_POSITION,l],[this.EVENTS.REACTIVE_EXPAND,a(p)],[this.EVENTS.MEDIA_SELECTION_START,a(f)],[this.EVENTS.REACTIVE_CALLOUT_START,a(h)],[this.EVENTS.ENGAGEMENT_INVITATION_SHOW,a(d)]]),v=Qg();v.proxyAll(b);var m=Yg();m.proxyAll(b),this.addUnbufferedEventListener=v.addEventListener,this.removeUnbufferedEventListener=v.removeEventListener,this.addBufferedEventListener=m.addEventListener,this.removeBufferedEventListener=m.removeEventListener,this.observable=function(e){return v.observable(e)},this.bufferedObservable=function(e){return m.observable(e)}};pN.prototype.EVENTS={REACTIVE_ENABLE:"overseer:reactive_enable",REACTIVE_DISABLE:"overseer:reactive_disable",REACTIVE_SET_POSITION:"overseer:reactive_set_position",REACTIVE_EXPAND:"overseer:reactive_expand",MEDIA_SELECTION_START:"overseer:media_selection_start",REACTIVE_CALLOUT_START:"overseer:reactive_callout_start",ENGAGEMENT_INVITATION_SHOW:"overseer:engagement_invitation_show"};var fN,hN=function(){function e(){s(this,e),this.EVENTS={ENGAGEMENT_REQUEST:"omnicall:engagement_request",PHONE_NUMBER_AVAILABLE:"omnicall:phone_number_available"};var t=k.fromPairs([[this.EVENTS.ENGAGEMENT_REQUEST,Gv.Observable.never()],[this.EVENTS.PHONE_NUMBER_AVAILABLE,Gv.Observable.never()]]),n=Qg();n.proxyAll(t),this.addEventListener=n.addEventListener,this.removeEventListener=n.removeEventListener,this.observable=function(e){return t[e]}}return c(e,[{key:"addEventListener",value:function(e,t){}},{key:"removeEventListener",value:function(e,t){}}]),e}(),dN=function e(){s(this,e),this.url=sm.conf.visitor_app.site_logo.url},bN=function(){function e(){s(this,e),this.visibleOperatorCount=sm.conf.visitor_app.reactive_tab.visible_operator_count,this.backColor=sm.conf.visitor_app.reactive_tab.back_color,this.fontSize=sm.conf.visitor_app.reactive_tab.font_size,this.format=sm.conf.visitor_app.reactive_tab.format,this.frontColor=sm.conf.visitor_app.reactive_tab.front_color,this.iconType=this._iconClassToType(sm.conf.visitor_app.reactive_tab.icon_class),this.placement=sm.conf.visitor_app.reactive_tab.placement,this.size=sm.conf.visitor_app.reactive_tab.size,this.text=sm.conf.visitor_app.reactive_tab.text,this.verticalOffset=sm.conf.visitor_app.reactive_tab.vertical_offset}return c(e,[{key:"_iconClassToType",value:function(e){switch(e){case"ico-voice":return"audio";case"ico-video":return"video";case"ico-text":return"text";default:return nm.error("Unknown icon class of the reactive tab",e),"video"}}}]),e}(),vN=function e(){s(this,e),this.apiUrl=sm.conf.api_url,this.alwaysUseDefaultOperatorPicture=sm.conf.visitor_app.always_use_default_operator_picture,this.visitorPageAdaption=sm.conf.visitor_app.visitor_page_adaption,this.engagementMode=function(e){switch(e.visitor_app.visitor_page_adaption){case"div":return"iframeless";case"iframe":return"iframed";case"style":return"nowrap";default:return"iframeless"}}(sm.conf),this.offlineMessagesEnabled=sm.conf.visitor_app.reactive_tab.contact_when_unstaffed,this.reactiveTabEnabled=sm.conf.visitor_app.reactive_tab.enabled,this.widgetMode=sm.conf.visitor_app.widget_mode,this.showReactiveTabWhenOperatorsUnavailable=sm.conf.visitor_app.reactive_tab.show_unavailable,this.theme=sm.conf.visitor_app.theme,this.isCustomTheme=sm.conf.visitor_app.is_custom_theme,this.locale=sm.conf.visitor_app.visitor_app_default_locale,this.reactiveTabVisuals=new bN,this.siteLogo=new dN,this.queuingEnabled=sm.conf.omniq.omniq_enabled,this.panelPosition=sm.conf.visitor_app.reactive_tab.position,this.phoneExtensionEnabled=sm.conf.visitor_app.phone_extension_enabled,this.phoneNumberDefaultCountry=sm.conf.visitor_app.phone_number_default_country,this.hideVisitorInfo=sm.conf.visitor_app.hide_visitor_info_in_visitor_app,this.enableVisitorTranscriptDownload=sm.conf.visitor_app.enable_visitor_transcript_download,this.watchForNewContactOperatorIntegrations=!1!==sm.conf.visitor_app.watch_for_new_contact_operator_integrations,this.engagementInvitationAudio=sm.conf.visitor_app.engagement_invitation_audio},mN=function(e,t,n,r){e||(e={}),n||(n=[]),r||(r=Gv.Scheduler.asap);var i=e,o=i.phone,s=i.email;if(!o&&!s)return Gv.Observable.throw({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Either phone or email must be specified"});var a=t.createApiRequestObservable,c=t.serverResponseTimeout;return a(k.pick(k.concat(["name","phone","email","message"],n),e)).map((function(){return{}})).catch((function(e){return Gv.Observable.throw(zI(e))})).timeoutWith(c,Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT,message:"Leave message request timed out"})),r).do(null,k.ifElse(k.propEq("cause",Ky.SALEMOVE.TOO_MANY_REQUESTS),nm.warn.bind(nm,"Leaving a message failed: too many requests"),nm.info.bind(nm,"Leaving a message failed"))).take(1)},yN=function(e,t){return function(e,t){return qg({method:"GET",url:e,responseType:"blob",getRequestHeaders:t})}(e,t).map((function(e){return e.response})).catch((function(e){return Gv.Observable.throw(zI(e))})).do(null,k.ifElse(k.propEq("cause",Ky.SALEMOVE.TOO_MANY_REQUESTS),nm.warn.bind(nm,"Requesting asset failed: too many requests"),nm.info.bind(nm,"Requesting asset failed"))).take(1)},gN=function(){function e(t){var n=t.id,r=t.api,i=t.operator,o=t.restrictedOperator,a=t.cobraObservable,c=t.channelObservable,u=t.message,l=t.logoUrl,p=t.platform,f=t.timeout,h=t.engagementApi,d=t.statsClient,b=t.communicationLib,v=t.notifyOfAccept,m=t.notifyOfDecline,y=t.createEngagement,g=t.cobraLoadTimeout,_=t.connectionStatusObservable,w=t.getRequestHeaders,E=t.internalVisitorStateObservable,O=t.volatileNotifications,S=t.statusObservable,T=t.pubsub,x=t.wsProxy;s(this,e),this.message=u,this.timeout=f,this.operator=o,this.logo={url:l};var A=new Gv.AsyncSubject,I=A.merge(ty(Gv.Observable.merge(r.canceledObservable.map(k.always(new ag({cause:Ky.SALEMOVE.CANCEL}))),r.timedOutObservable.map(k.always(new ag({cause:Ky.SALEMOVE.TIMEOUT})))))).take(1).flatMap((function(e){return a.map((function(t){return k.merge({cobra:t},e)})).take(1).timeoutWith(g,Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR,message:"Cobra load timeout exceeded"})).do(null,(function(e){return nm.warn("Cobra loading timed out",{error:e})}))).do(null,(function(t){return nm.warn("Loading cobra failed, ending engagement",{error:t}),h.endEngagement({engagementId:e.engagementId,reason:"error",subReason:"visitor_cobra_load_failure"}).take(1).subscribe(nm.log.bind(nm,"Successfully ended engagement after cobra load failure"),nm.warn.bind(nm,"Failed to end engagement after cobra load failure"))})).map((function(e){var t=e.engagementId,n=e.subEngagementId,r=e.media,o=e.cobra,s=e.createdAt;return y({operator:i,engagementId:t,subEngagementId:n,startingMedia:r,type:"proactive",isReestablishing:!1,initialChatHistoryObservable:Ix(t),communicationLib:b,statsClient:d,cobra:o,channelObservable:c,platform:p,engagementApi:h,connectionStatusObservable:_,getRequestHeaders:w,internalVisitorStateObservable:E,entrypoint:"proactive-request",volatileNotifications:O,statusObservable:S,pubsub:T,wsProxy:x,createdAt:s})})).do((function(e){return e.start()})).catch(lg)}));this.engagementPromise=I.toPromise(),this.accept=function(){return r.acknowledge({id:n}).do((function(){return v({engagement_request_id:n,operator:i})})).do((function(){return nm.info("Engagement: Proactive request accepted",{operator:i})})).mapTo({}).catch(lg).toPromise()},this.selectMedia=function(e,t){if(p===rg&&"text"!==e)return Promise.reject(new ag({cause:Ky.SALEMOVE.NOT_SUPPORTED,message:"OmniBrowse engagements only support text media."}));var s=o.state.medias,a=ok(o.state.oneWayMedias),c=t||{},u=c.phoneNumber,l=c.phoneExtension,f=c.oneWay;return PA({options:t,availableMediaTypes:s,availableOneWayMediaTypes:a,media:e}).then((function(){return v({engagement_request_id:n,operator:i}),r.accept({id:n,selectedMedia:e,mediaOptions:{phoneNumber:u,phoneExtension:l,oneWay:f}}).do((function(){sm.logger.info("Engagement: Proactive request media selected",arguments[0])})).map((function(t){return k.merge(t,{media:e})})).do(A).mapTo({}).catch(lg).toPromise()}))},this.decline=function(){return r.decline({id:n}).do((function(){return m({operator:i})})).do((function(){return A.error(new ag({cause:Ky.SALEMOVE.DECLINE}))})).do((function(){return sm.logger.info("Engagement, Proactive request declined",arguments[0])})).mapTo({}).catch(lg).toPromise()}}return c(e,null,[{key:"create",value:function(t){var n=t.api,r=t.id,i=t.operator,o=t.restrictedOperator,s=t.message,a=t.logoUrl,c=t.platform,u=t.timeout,l=t.statsClient,p=t.cobraObservable,f=t.channelObservable,h=t.engagementApi,d=t.connectionStatusObservable,b=t.getRequestHeaders,v=t.internalVisitorStateObservable,m=t.volatileNotifications,y=t.statusObservable,g=t.pubsub,_=t.wsProxy;return new e({api:n,id:r,statsClient:l,communicationLib:sm.conf.communications.lib,createEngagement:eN.create,cobraObservable:p,operator:i,restrictedOperator:o,platform:c,timeout:u,message:s,logoUrl:a,cobraLoadTimeout:1e4,notifyOfAccept:bm.vent.trigger.bind(bm.vent,bm.MSG.PROACTIVE_ACCEPT),notifyOfDecline:bm.vent.trigger.bind(bm.vent,bm.MSG.PROACTIVE_DECLINE),channelObservable:f,engagementApi:h,connectionStatusObservable:d,getRequestHeaders:b,internalVisitorStateObservable:v,volatileNotifications:m,statusObservable:y,pubsub:g,wsProxy:_})}}]),e}(),_N=["engagement","engagements"],wN=["engagement","requests"],EN=["visitor","browser_tab_id"],ON=function(e){return k.any(k.propEq("id",sm.siteId),e.transferrable_sites)},SN=function(e){var t=k.pathOr([],_N,e);try{return k.filter(ON,t)[0]}catch(n){return void nm.error("Engagement was undefined in internalVisitorState",{internalVisitorState:e,engagements:t})}},TN=function(e){return ON(e)&&k.path(EN,e)===sm.tabId},kN=k.compose(k.nth(0),k.filter(TN),k.pathOr([],_N)),xN=k.compose(k.nth(0),k.filter(k.complement(TN)),k.pathOr([],_N)),AN=k.compose(k.nth(0),k.filter(k.allPass([ON,k.propEq("outcome",null),k.propEq("type","reactive")])),k.pathOr([],wN)),IN=function(e,t){return t.filter((function(t){var n=function(e,t){return k.compose(k.find(k.propEq("id",e)),k.pathOr([],wN))(t)}(e.id,t);return Boolean(n.outcome)})).take(1).map((function(t){var n=kN(t);return n&&n.operator.id===e.operator.id?n:null})).filter(k.identity)},NN=function(e){var t=e.channelObservable,n=e.internalVisitorStateObservable,r=e.statusObservable,i=e.webRtcMode,o=e.enabledMediaLevel,s=e.statsClient,a=e.cobraObservable,c=e.isEngagedObservable,u=e.engagementApi,l=e.connectionStatusObservable,p=e.getRequestHeaders,f=e.volatileNotifications,h=e.pubsub,d=e.wsProxy,b=e.dynamicImport;return function(e){var t=e.reestablishRequestObservable,n=e.channelObservable,r=e.statusObservable,i=e.cobraObservable,o=e.isEngagedObservable;return t.switchMap((function(e){var t=r.filter(k.equals({})),o=n.filter(k.compose(k.propEq("id",e.operatorId),k.prop("operator"))).take(1).mapTo(e).takeUntil(t),s=i.filter(k.pathEq(["operator","id"],e.operatorId)).pluck("cobraSource").take(1);return Gv.Observable.combineLatest(o,s,(function(e,t){return k.merge(e,{cobra:t})}))})).withLatestFrom(o,(function(e,t){return{engagementReestablishMessage:e,isEngaged:t}})).do((function(e){e.isEngaged?nm.info("Found an ongoing engagement during engagement reestablishing, skipping"):nm.info("Reestablishing ongoing engagement")})).filter((function(e){return!e.isEngaged})).map((function(e){return e.engagementReestablishMessage}))}({reestablishRequestObservable:function(e){var t=e.bufferCount(2,1).map((function(e){var t=g(e,2),n=t[0],r=t[1],i=xN(n),o=kN(r);return o&&(i||n.visitor_id!==r.visitor_id)?o:null})).filter(k.identity);return e.take(1).flatMap((function(t){var n=Gv.Observable.of(t).map(kN).filter(k.identity),r=AN(t),i=r?IN(r,e):Gv.Observable.empty();return Gv.Observable.merge(n,i)})).merge(t).map((function(e){return{id:e.id,platform:e.platform,subEngagementId:e.sub_engagement_legacy_id,channelUrl:e.channel_url,operatorId:e.operator.id,operatorName:e.operator.name,operatorFormattedName:e.operator.formatted_name,operatorMediaType:e.operator.media_type,operatorPicture:{url:e.operator.picture_url},entrypoint:e.entrypoint,createdAt:e.start_time}}))}(n),channelObservable:t,statusObservable:r,cobraObservable:a,isEngagedObservable:c}).flatMap((function(e){return b("Comms").mapTo(e)})).map((function(e){var a=jk({id:e.operatorId,name:e.operatorName,formattedName:e.operatorFormattedName,picture:e.operatorPicture,mediaType:e.operatorMediaType,webRtcMode:i,enabledMediaType:o}),c=eN.create({engagementId:e.id,subEngagementId:e.subEngagementId,initialChatHistoryObservable:Ix(e.id),operator:a,isReestablishing:!0,mediaState:e.mediaState,platform:e.platform,communicationLib:sm.conf.communications.lib,statsClient:s,cobra:e.cobra,channelObservable:t,engagementApi:u,connectionStatusObservable:l,getRequestHeaders:p,internalVisitorStateObservable:n,entrypoint:e.entrypoint,volatileNotifications:f,statusObservable:r,pubsub:h,wsProxy:d,createdAt:e.createdAt});return c.start(),{engagement:c,platform:e.platform}}))},CN=function(e){var t=e.replayedReestablishObservable,n=e.defaultHandler,r=e.storeKey,i=e.platform,o=e.sessionStore,s=e.timeout,a=new rN,c=t.filter(k.propEq("platform",i)).map(k.prop("engagement")),u=function(e){return a.add(c.subscribe(e,nm.error))},l=new Gv.Subject;return u((function(e){return o.get(r)?Gv.Observable.timer(s).takeUntil(l).subscribe((function(){return o.remove(r),nm.error("Waited for custom reestablish handler to be set, but it wasn't set before timeout."),l.subscribe((function(){return nm.error("Custom reestablish handler was set, but after timeout."),console.error("Salemove#setEngagementReestablishHandler() was called too late!"+" Glia waits ".concat(Math.round(15)," seconds after page load")+" for the custom reestablish handler to be set. Executing the handler anyway, although the default handler has already been called.")})),n(e)})):n(e)})),function(e){u(e),l.next(e),o.set(r,!0)}},RN=function e(t){var n=t.engaged,r=t.name,i=t.email;s(this,e),this.engaged=n,this.name=r,this.email=i},PN=function e(t){var n=t.connected;s(this,e),this.connected=n},MN="__sm_mutation_event_trigger_flip__",jN=new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR}),LN=function(e,t){var n=e.wsProxy,r=e.stats,i=e.apiTimeoutMilliseconds;t||(t=Gv.Scheduler.asap);var o=Ig({stats:r,protocol:"rest",failureTagProperty:"message",timeout:i,timeoutError:Gv.Observable.throw(jN),scheduler:t});return{createMediaUpgrade:function(e){var t=e.engagementId,r=e.media;return o({resource:"media-upgrade",method:"create"},(function(){return n.request({method:"POST",url:"".concat(sm.conf.api_url,"/engagements/").concat(t,"/media_upgrades"),payload:{media:r},headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json"}})}))},getChatTranscript:function(e){return o({resource:"chat-transcript",method:"fetch"},(function(){return n.request({method:"GET",url:"".concat(sm.conf.api_url,"/engagements/").concat(e,"/chat_transcript"),payload:null,headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json"}})}))},endEngagement:function(e){var t=e.engagementId,r=k.compose(k.assoc("action","end"),zy({subReason:"sub_reason"}),k.pick(["reason","subReason"]))(e);return o({resource:"engagement",method:"end"},(function(){return n.request({method:"PATCH",url:"".concat(sm.conf.api_url,"/engagements/").concat(t),payload:r,headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json"}})}))}}},qN=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),UN={"'operator_id' Operator is not available to be engaged":Ky.SALEMOVE.OPERATOR_UNAVAILABLE,"Operator cannot be engaged":Ky.SALEMOVE.OPERATOR_UNAVAILABLE,"Visitor cannot be engaged":Ky.SALEMOVE.ALREADY_ENGAGED,"'engagement_request_id' already failed":Ky.SALEMOVE.CONFLICT,"'engagement_request_id' already accepted":Ky.SALEMOVE.CONFLICT,"'engagement_request_id' already acknowledged":Ky.SALEMOVE.CONFLICT},DN=(u(fN={},403,Ky.SALEMOVE.FORBIDDEN),u(fN,409,Ky.SALEMOVE.CONFLICT),fN),VN=["'engagement_request_id' already failed","'engagement_request_id' already accepted","'engagement_request_id' already acknowledged"],FN=function(e,t,n){var r=k.merge(n,{error:e});e&&k.contains(e.message,VN)||e instanceof ag?nm.warn("Failed to ".concat(t," engagement request"),r):nm.error("Failed to ".concat(t," engagement request"),r)},BN=function(e){var t=UN[e&&e.message]||DN[e&&e.status]||Ky.SALEMOVE.INTERNAL_ERROR;return new ag({cause:t})},HN=function(e,t){var n=e.wsProxy,r=e.stats,i=e.apiTimeoutMilliseconds,o=e.visitorMetadata,s=e.internalVisitorStateObservable;t||(t=Gv.Scheduler.asap);var a=Ig({stats:r,protocol:"rest",failureTagProperty:"cause",timeout:i,timeoutError:Gv.Observable.throw(qN),scheduler:t}),c=function(e){var t=e.id,r=e.data;return n.request({method:"PATCH",url:"".concat(sm.conf.api_url,"/engagement_requests/").concat(t),payload:r,headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json","x-salemove-tab-id":sm.tabId}})},u=function(e){r.increment("engagement.flow",["entrypoint:proactive-request","stage:requested","action:end"].concat(e))},l=s.map(SN).bufferCount(2,1).filter((function(e){var t=g(e,2),n=t[0],r=t[1];return!n&&Boolean(r)})).map((function(e){var t=g(e,2);t[0];return t[1]})),p=l.filter(TN).do((function(e){var t=e.id;return nm.info("Found new accepted engagement",{engagement_id:t})})).map((function(e){return{engagementId:e.id,subEngagementId:e.sub_engagement_legacy_id,operatorId:e.operator.id,operatorMediaType:e.operator.media_type,operatorName:e.operator.name,operatorFormattedName:e.operator.formatted_name,operatorPicture:{url:e.operator.picture_url},media:TA(e.media),entrypoint:e.entrypoint,platform:e.platform,createdAt:e.start_time}})),f=l.filter(k.complement(TN)).mapTo({}),h=function(e){var t=k.propEq("site_id",sm.siteId);return k.compose(k.filter(t),k.pathOr([],["engagement","requests"]))(e)},d=k.compose(k.nth(0),k.filter(k.propEq("outcome",null)),h),b=function(e){return k.compose(k.nth(0),k.filter(k.propEq("id",e)),h)},v=s.map(d).filter(k.identity),m=k.curry((function(e,t){return s.map(b(t.id)).filter(k.identity).filter((function(t){return k.contains(t.outcome,e)})).take(1).takeUntil(function(e,t){return s.map(b(e.id)).filter(k.identity).filter((function(e){return!k.contains(e.outcome,t)}))}(t,k.append(null,e)))})),y=v.flatMap(m(["operator_cancel","operator_left"])).mapTo({}),_=Gv.Observable.merge(f,y),w=v.flatMap(m(["timed_out"])).mapTo({});return{create:function(e){var t=e.operatorId,r=e.siteId,i=e.media,s=e.source,c=e.mediaOptions,u={operator_id:t,site_id:r,media:i,source:s||"sdk",visitor_metadata:o,media_options:{phone_number:c.phoneNumber,phone_extension:c.phoneExtension,one_way:c.oneWay}};return nm.info("Engagement: Sending reactive request",u),a({resource:"engagement-request",method:"create"},(function(){return(e=u,n.request({method:"POST",url:"".concat(sm.conf.api_url,"/engagement_requests"),payload:e,headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json","x-salemove-tab-id":sm.tabId}})).map((function(e){var t=e.timeout;return{engagementRequestId:e.id,acknowledgeTimeoutSeconds:t}})).catch((function(e){var n={error:e,operator_id:t,site_id:r,media:i,source:s,media_options:c};return e instanceof ag?(nm.info("Failed to create engagement request",n),Gv.Observable.throw(e)):(403===(e&&e.status)?nm.info("Visitor forbidden to create engagement request",n):422===(e&&e.status)?nm.info("Operator is not available to be engaged",n):409===(e&&e.status)?nm.info("Operator cannot be engaged",n):nm.error("Failed to create engagement request",n),Gv.Observable.throw(BN(e)))}));var e}))},cancel:function(e){var t=e.id,n="cancel";return a({resource:"engagement-request",method:n},(function(){return c({id:t,data:{action:n}}).catch((function(e){return FN(e,n,{engagement_request_id:t}),Gv.Observable.throw(BN(e))}))}))},acknowledge:function(e){var t=e.id,n="acknowledge";return a({resource:"engagement-request",method:n},(function(){return c({id:t,data:{action:n}}).catch((function(e){return FN(e,n,{engagement_request_id:t}),Gv.Observable.throw(BN(e))})).do(null,(function(e){e.cause===Ky.SALEMOVE.INTERNAL_ERROR?u(["reason:internal-error"]):e.cause!==Ky.SALEMOVE.CONFLICT&&u(["reason:unknown"])}))}))},accept:function(e){var t=e.id,n=e.selectedMedia,r=e.mediaOptions,i="accept";return a({resource:"engagement-request",method:i},(function(){return c({id:t,data:{action:i,media:n,media_options:{phone_number:r.phoneNumber,phone_extension:r.phoneExtension,one_way:r.oneWay},visitor_metadata:o}}).catch((function(e){return FN(e,i,{engagement_request_id:t,media:n,media_options:r}),Gv.Observable.throw(BN(e))})).do(null,(function(e){e.cause===Ky.SALEMOVE.INTERNAL_ERROR?u(["reason:internal-error"]):e.cause!==Ky.SALEMOVE.CONFLICT&&u(["reason:unknown"])})).map(zy({engagement_id:"engagementId",sub_engagement_id:"subEngagementId",created_at:"createdAt"}))}))},decline:function(e){var t=e.id,n="decline";return a({resource:"engagement-request",method:n},(function(){return c({id:t,data:{action:n}}).catch((function(e){return FN(e,n,{engagement_request_id:t}),Gv.Observable.throw(BN(e))}))}))},notifyOfReactiveFailure:function(e){var t=e.id;return a({resource:"engagement-request",method:"cancel-due-to-error"},(function(){return c({id:t,data:{action:"cancel",reason:"error"}}).catch((function(e){return Gv.Observable.throw(BN(e))})).do(null,nm.warn.bind(nm,"Failed to cancel reactive engagement request due to error"))}))},acceptedObservable:p,declinedObservable:v.flatMap(m(["rejected"])).mapTo({}),canceledObservable:_,timedOutObservable:w}},WN=["name","email","phone","note","customAttributes","customAttributesUpdateMethod"],GN={customAttributes:"custom_attributes",customAttributesUpdateMethod:"custom_attributes_update_method"},zN="last_known_ci:".concat(Xv()),JN=function(e){var t=Jv(),n=JSON.stringify(e);return function(e){for(var t=0,n=0,r=e.length;n3&&void 0!==arguments[3]?arguments[3]:XN,s=o.setTimeout,a=o.clearTimeout,c=function(e){return r=e,i&&a(i),i=s((function(){r=void 0}),t),e};return function(){return r?(n(r),Promise.resolve(r)):e().then(c)}},ZN=function e(t){var n=t.state,r=t.medias,i=t.transitionReason,o=t.ticket,a=t.activeTicket;s(this,e),this.state=n,this.medias=r,this.transitionReason=i,this.ticket=o,this.activeTicket=a};ZN.prototype.QUEUE_STATES={CAN_QUEUE:"can_queue",CANNOT_QUEUE:"cannot_queue",QUEUED:"queued"},ZN.prototype.TRANSITION_REASONS={ENGAGED:"engaged",CANCELED:"canceled",UNSTAFFED:"unstaffed",CLOSED:"closed",DISCONNECTED:"disconnected",FAILED:"failed",ALREADY_QUEUED:"already_queued",FORBIDDEN:"forbidden"};var eC=function e(t){var n=t.averageDurationInSeconds;s(this,e),this.averageDurationInSeconds=n},tC=new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR}),nC=new ag({cause:Ky.SALEMOVE.CANCEL}),rC=function(e,t){return e.increment("engagement.flow",["entrypoint:queue-request"].concat(t))},iC=function(e){var t=e.wsProxy,n=e.statsClient,r=e.apiTimeoutMilliseconds,i=e.ticket_id;return function(e,t){return Ig({stats:e,protocol:"rest",failureTagProperty:"error",timeout:t,timeoutError:Gv.Observable.throw(tC)})}(n,r)({resource:"queue_tickets",method:"delete"},(function(){return t.request({method:"DELETE",url:"".concat(sm.conf.api_url,"/queue_tickets/").concat(i),payload:{},headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json"}})})).mapTo({}).do((function(){return function(e){return rC(e,["stage:requested","action:end","expected:true","reason:cancel"])}(n)})).catch(lg)},oC=function(e){var t=e.engagementApi,n=e.engagementRequestApi,r=e.cobraObservable,i=e.fetchEngagementDependencies,o=e.channelObservable,s=e.communicationLib,a=e.statsClient,c=e.webRtcMode,u=e.enabledMediaLevel,l=e.connectionStatusObservable,p=e.getRequestHeaders,f=e.internalVisitorStateObservable,h=e.volatileNotifications,d=e.pubsub,b=e.statusObservable,v=e.wsProxy,m=Gv.Observable.combineLatest(r,i(),(function(e){return{cobra:e}})).publishReplay(1),y=m.connect();return n.acceptedObservable.take(1).flatMap((function(e){var n=e.engagementId,r=e.subEngagementId,i=e.operatorId,y=e.media,g=e.operatorName,_=e.operatorFormattedName,w=e.operatorPicture,E=e.operatorMediaType,O=e.entrypoint,S=e.createdAt;return m.take(1).map((function(e){var m=e.cobra,T=jk({id:i,name:g,formattedName:_,picture:w,mediaType:E,webRtcMode:c,enabledMediaType:u});return{engagementId:n,subEngagementId:r,startingMedia:y,type:"reactive",isReestablishing:!1,initialChatHistoryObservable:Ix(n),operator:T,cobra:m,channelObservable:o,communicationLib:s,engagementApi:t,getRequestHeaders:p,internalVisitorStateObservable:f,entrypoint:O,volatileNotifications:h,pubsub:d,statusObservable:b,wsProxy:v,createdAt:S,statsClient:a,connectionStatusObservable:l}})).map(eN.create).do(null,(function(){return function(e){return rC(e,["stage:requested","action:end","reason:script-load-error"])}(a)})).do(null,(function(){return t.endEngagement({engagementId:n,reason:"error",subReason:"setup_failed"})}))})).finally((function(){return y.unsubscribe()}))},sC=function(){function e(t){s(this,e);var n=t.ticket_id,r=t.apiTimeoutMilliseconds,i=t.statsClient,o=t.wsProxy,a=t.stopObservable,c=new Gv.Subject,u=Gv.Observable.merge(c,a);nm.info("Queue Ticket created, waiting for engagement",{queue_ticket_id:n});var l=oC(t).takeUntil(u).do((function(e){return e.start()})).catch(lg).publishReplay(1);l.connect(),this.engagementPromise=l.merge(u.flatMapTo(Gv.Observable.throw(nC))).take(1).toPromise(),this.cancel=function(){return c.next(),l.last(null,null,null).flatMap((function(e){return e?Gv.Observable.fromPromise(e.end()):iC({wsProxy:o,statsClient:i,apiTimeoutMilliseconds:r,ticket_id:n})})).toPromise()}}return c(e,null,[{key:"create",value:function(t,n){var r=new Gv.Subject;return{ticket:k.compose(k.construct(e),k.assoc("stopObservable",r.asObservable()))(k.merge(t,{ticket_id:k.path(["activeTicket","id"],n)})),subscription:new Gv.Subscription((function(){return r.next(),r.unsubscribe()}))}}}]),e}(),aC="requesting",cC="created",uC={open:1,opened:1,full:2,unstaffed:3,closed:4},lC=k.compose(k.reduce(k.minBy((function(e){return uC[e]})),"closed"),k.map(k.path(["state","status"]))),pC=k.compose(k.uniq,k.chain(k.path(["state","medias"]))),fC=function(e){var t=k.filter(k.pathEq(["state","status"],"open"),e),n=pC(t);return{state:lC(e)||"closed",medias:n}},hC=function(e){return k.pick(Object.getOwnPropertyNames(e),e)},dC=["enqueued","request_sent"],bC=k.propEq("site_id",sm.siteId),vC=k.compose(k.filter(bC),k.pathOr([],["omniq","queue_tickets"])),mC=k.compose(k.nth(0),k.filter((function(e){return-1!==dC.indexOf(e.state)})),vC),yC=k.curry((function(e,t){return k.compose(k.nth(0),k.filter(k.propEq("id",e)),vC)(t)})),gC=function(e){var t=e.queueState,n=e.queued,r=e.enqueuedInCurrentTab;return n||!(k.isNil(t)||k.isNil(n)||k.isNil(r))},_C=function(e,t){return k.intersection(function(e){var t=["text","phone"];return e&&(t=t.concat(["messaging"])),Ek()===wk&&(t=t.concat(["audio","video"])),t}(t),e)},wC=function(e){var t=e.queueState,n=e.queued,r=e.visitorLeftReason,i=e.enqueuedInCurrentTab,o=e.isEngaged,s=e.activeTicket,a=e.isVisitorAuthenticatedExternally;if(n)return new ZN(i?{state:ZN.prototype.QUEUE_STATES.QUEUED,activeTicket:s}:{state:ZN.prototype.QUEUE_STATES.CANNOT_QUEUE,transitionReason:ZN.prototype.TRANSITION_REASONS.ALREADY_QUEUED});var c=function(e,t){if(t)return ZN.prototype.TRANSITION_REASONS.ENGAGED;if(e)switch(e){case"finished":return ZN.prototype.TRANSITION_REASONS.ENGAGED;case"canceled":return ZN.prototype.TRANSITION_REASONS.CANCELED;case"unstaffed":return ZN.prototype.TRANSITION_REASONS.UNSTAFFED;case"closed":return ZN.prototype.TRANSITION_REASONS.CLOSED;case"disconnected":return ZN.prototype.TRANSITION_REASONS.DISCONNECTED;case"failure":return ZN.prototype.TRANSITION_REASONS.FAILED;case"forbidden":return ZN.prototype.TRANSITION_REASONS.FORBIDDEN;case"visitor_conflict":return ZN.prototype.TRANSITION_REASONS.FAILED;default:return void nm.error("Unknown visitor left reason",{reason:e})}}(r,o);if(c===ZN.prototype.TRANSITION_REASONS.ENGAGED||"opened"!==t.state&&"open"!==t.state)return new ZN({state:ZN.prototype.QUEUE_STATES.CANNOT_QUEUE,transitionReason:c});var u=_C(t.medias,a);return 0===u.length?new ZN({state:ZN.prototype.QUEUE_STATES.CANNOT_QUEUE,transitionReason:c}):new ZN({state:ZN.prototype.QUEUE_STATES.CAN_QUEUE,medias:u,transitionReason:c})},EC=k.both(k.propEq("state",ZN.prototype.QUEUE_STATES.CANNOT_QUEUE),k.propEq("transitionReason",ZN.prototype.TRANSITION_REASONS.ENGAGED)),OC=function(e){var t=e.routingObservable,n=e.internalVisitorStateObservable,r=e.visitorAuthenticatedExternallyObservable,i=e.queuesStateUpdatesObservable,o=e.createQueueTicketStateObservable,s=e.queueTicketBindings,a=e.scheduler;if(a||(a=Gv.Scheduler.asap),k.path(["conf","omniq","omniq_enabled"],sm)){var c=new Gv.ReplaySubject(1);o.subscribe((function(e){return c.next(!k.contains(e,[aC,cC]))}));var u=function(e,t){return e.publish((function(e){return e.combineLatest(t,(function(e,t){return t})).filter((function(e){return e})).publish((function(t){return e.bufferWhen((function(){return t.take(1)}))}))})).flatMap((function(e){return Gv.Observable.from(e)}))}(function(e){var t=e.routingObservable,n=e.queuesStateUpdatesObservable;return t.switchMap((function(e){var t=e.queue_ids;return k.not(t)?vt([]):n.subscribeToListAsObservable({queueIds:t})})).map(fC).map(k.objOf("queueState")).distinctUntilChanged(k.equals)}({routingObservable:t,queuesStateUpdatesObservable:i}),c),l=Gv.Observable.combineLatest(n,r).scan((function(e,t){var n,r,i,o=g(t,2),s=o[0],a=o[1],c=e&&e.activeTicket&&e.activeTicket.id,u=mC(s),l=Boolean(SN(s));return u?{queued:!0,enqueuedInCurrentTab:(r=u,i=k.lensPath(["visitor","browser_tab_id"]),k.compose(k.equals(sm.tabId),k.view(i))(r)),activeTicket:{id:u.id},visitorLeftReason:null,isEngaged:l,isVisitorAuthenticatedExternally:a}:c&&(n=yC(c,s))?{queued:!1,enqueuedInCurrentTab:!1,activeTicket:null,visitorLeftReason:n.state,isEngaged:l,isVisitorAuthenticatedExternally:a}:{queued:!1,enqueuedInCurrentTab:!1,activeTicket:null,visitorLeftReason:null,isEngaged:l,isVisitorAuthenticatedExternally:a}}),{}).do((function(e){e.queued||c.next(!0)})).distinctUntilChanged(k.equals);return{aggregateQueueStateObservable:Gv.Observable.merge(u,l).scan(k.merge,{}).filter(gC).do((function(e){sm.conf.visitor_api.enable_staffing_logs&&nm.info("[staffing-logs] Recording raw aggregate queue state",e)})).map(wC).distinctUntilChanged(k.equals,hC).scan(function(e){return function(t,n){var r;if(n.state===ZN.prototype.QUEUE_STATES.QUEUED){var i;t.subscription.unsubscribe();var o=sC.create(e,n);return i=o.ticket,r=o.subscription,n.ticket=i,{queueState:n,subscription:r}}return EC(n)?(nm.info("Discarding queue ticket subscription as Visitor got engaged"),{queueState:n,subscription:Gv.Subscription.EMPTY}):(t.subscription!==Gv.Subscription.EMPTY&&nm.info("Dispose queue ticket subscription as Visitor is no longer queued"),t.subscription.unsubscribe(),{queueState:n,subscription:Gv.Subscription.EMPTY})}}(s),{subscription:Gv.Subscription.EMPTY}).map(k.prop("queueState")).publishReplay(1,Number.POSITIVE_INFINITY,a).refCount()}}return{aggregateQueueStateObservable:Gv.Observable.empty()}},SC=function(e){return e&&e.cause===Ky.SALEMOVE.FORBIDDEN||e&&e.cause===Ky.SALEMOVE.INVALID_INPUT?["reason:invalid-input"]:["reason:unknown"]},TC=[],kC=function(e){l(n,e);var t=m(n);function n(e){var r;return s(this,n),e||(e={}),(r=t.apply(this,arguments)).ticket=e.ticket,r}return n}(ag),xC=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),AC=function(e){return!function(e){return 0===e}(e.status)?!function(e){return 403===e}(e.status)?"Service Unavailable"===e.errorThrown&&(e=new ag({cause:Ky.SALEMOVE.INTERNAL_ERROR})):e=new ag({cause:Ky.SALEMOVE.FORBIDDEN}):e=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),Gv.Observable.throw(e)},IC=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{logResponse:!0},r=n.logResponse;return Ig({stats:e,protocol:"rest",failureTagProperty:"error",timeout:t,timeoutError:Gv.Observable.throw(xC),logResponse:r})},NC=function(e,t){return e.omniq.omniq_enabled?t():Promise.reject(new ag({cause:Ky.SALEMOVE.DISABLED}))},CC=function(e){var t=e.conf,n=e.statsClient,r=e.apiTimeoutMilliseconds;return function(){return NC(t,(function(){return IC(n,r)({resource:"queue_wait_duration",method:"get"},(function(){return qg({url:xx("/engagements/queue/wait_duration"),responseType:"json"})})).map(k.compose(k.construct(eC),zy({average_duration_in_seconds:"averageDurationInSeconds"}),k.map(Math.floor),k.prop("response"))).catch((function(e){return Gv.Observable.throw(zI(e))})).catch(lg).toPromise()}))}},RC=k.compose((function(e){var t=e.id,n=e.name,r=e.status,i=e.availableProperties;return new Yy({id:t,name:n,status:r,medias:i.media})}),k.evolve({status:Qy}),k.pick(["id","name","status","availableProperties"])),PC=function(e){var t=e.conf,n=e.wsProxy,r=e.statsClient,i=e.apiTimeoutMilliseconds,o=e.apiMaxRetries,s=e.apiRetryIntervalMilliseconds;return function(){var e=function(e){return k.not(k.contains(e.status,k.range(400,499)))};return NC(t,(function(){var t=Gv.Observable.defer((function(){return IC(r,i,{logResponse:!1})({resource:"queues",method:"get"},(function(){return n.request({method:"GET",url:"".concat(sm.conf.api_url,"/queues?site_ids[]=").concat(sm.siteId),payload:null,headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json"}})}))}));return ry(t,{maxRetries:o,calculateDelay:A(s),shouldRetry:e}).map(k.prop("queues")).map(k.map(zy({available_properties:"availableProperties"}))).map(k.map(RC)).catch(AC).catch(lg).toPromise()}))}},MC=function(e){var t=e.wsProxy,n=e.pubsub,r=e.routingObservable,i=e.engagementApi,o=e.engagementRequestApi,s=e.operatorsObservable,a=e.cobraObservable,c=e.channelObservable,u=e.communicationLib,l=e.statsClient,p=e.fetchEngagementDependencies,f=e.apiTimeoutMilliseconds,h=e.apiRetryIntervalMilliseconds,d=e.apiMaxRetries,b=e.connectionStatusObservable,v=e.webRtcMode,m=e.enabledMediaLevel,y=e.visitorMetadata,_=e.conf,w=e.getRequestHeaders,E=e.internalVisitorStateObservable,O=e.visitorAuthenticatedExternallyObservable,S=e.volatileNotifications,T=e.statusObservable,x=e.queuesStateUpdatesObservable,A=new Gv.Subscription;A.add(r.subscribe((function(e){TC=e.queue_ids})));var I=function(e){return l.increment("engagement.flow",["entrypoint:queue-request"].concat(e))},N=new Gv.Subject,C=OC({routingObservable:r,internalVisitorStateObservable:E,visitorAuthenticatedExternallyObservable:O,queuesStateUpdatesObservable:x,createQueueTicketStateObservable:N,queueTicketBindings:{apiTimeoutMilliseconds:f,statsClient:l,wsProxy:t,engagementApi:i,engagementRequestApi:o,cobraObservable:a,fetchEngagementDependencies:p,operatorsObservable:s,channelObservable:c,communicationLib:u,webRtcMode:v,enabledMediaLevel:m,connectionStatusObservable:b,getRequestHeaders:w,internalVisitorStateObservable:E,volatileNotifications:S,pubsub:n,statusObservable:T}}).aggregateQueueStateObservable,R=function(e,t){return C.take(1).flatMap((function(n){var r=n.state,i=n.medias;return r===ZN.prototype.QUEUE_STATES.CAN_QUEUE?function(e){var t=e.media,n=e.options,r=e.availableMediaTypes;return PA({media:t,options:n,availableMediaTypes:r,availableOneWayMediaTypes:ok(r)})}({media:e,options:t,availableMediaTypes:i}):Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.FORBIDDEN,message:"Queue state must be: ".concat(ZN.prototype.QUEUE_STATES.CAN_QUEUE)}))}))},P=function(){return E.take(1).flatMap((function(e){return Boolean(SN(e))?Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.FORBIDDEN,message:"Visitor is already engaged"})):Gv.Observable.of({})}))},M=function(e){return-1!==["Queue is closed","Queue is full"].indexOf(e.details)?Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:e.message})):409===e.status?C.take(1).flatMap((function(e){return function(e){return Gv.Observable.throw(new kC({cause:Ky.SALEMOVE.ALREADY_QUEUED,message:"Visitor is already queued",ticket:e}))}(e.ticket)})):403===e.status?Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.FORBIDDEN})):"Validation error"===e.error?Gv.Observable.throw(new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:e.error})):lg(e)};return{subscription:A,queueForEngagement:function(e,n){return n||(n={}),I(["action:begin"]),NC(_,(function(){var r=g(n.queueId?[{media:e,options:n},P]:[{media:e,options:n,queueIds:TC},R],2),i=r[0],o=r[1],s=function(e){var t=e.wsProxy,n=e.statsClient,r=e.apiTimeoutMilliseconds,i=e.errorHandling,o=e.visitorMetadata;return function(e){var s=e.media,a=e.options,c=e.queueIds;return IC(n,r)({resource:"queue_tickets",method:"create"},(function(){var e={};a.phoneNumber&&(e.phone_number=a.phoneNumber),a.phoneExtension&&(e.phone_extension=a.phoneExtension),a.oneWay&&(e.one_way=a.oneWay);var n=a.source||"sdk",r={media:s,visitor_id:Jv(),media_options:e,source:n,visitor_metadata:o};a.queueId?r=k.merge(r,{queue_id:a.queueId}):c&&(r=k.merge(r,{queue_ids:c}));var u={method:"POST",url:"".concat(sm.conf.api_url,"/queue_tickets"),payload:k.merge(r,{site_id:sm.siteId}),headers:{"content-type":"application/json",accept:"application/vnd.salemove.v1+json","x-salemove-tab-id":sm.tabId}};return t.request(u).catch(i||lg)}))}}({wsProxy:t,statsClient:l,apiTimeoutMilliseconds:f,visitorMetadata:y,errorHandling:M})(i);return o(e,n).do((function(){return N.next(aC)})).do((function(){return I(["action:reach","stage:create-request"])}),(function(e){return I(["action:end","stage:pre-request"].concat(SC(e)))})).flatMapTo(s).mapTo({}).do((function(){return I(["action:reach","stage:requested"])}),(function(e){return I(["action:end","stage:create-request"].concat(SC(e)))})).do((function(){return N.next(cC)}),(function(){return N.next("failed-to-create")})).toPromise()}))},fetchWaitDuration:CC({conf:_,statsClient:l,apiTimeoutMilliseconds:f}),aggregateQueueStateObservable:C,getQueues:$N(PC({conf:_,wsProxy:t,statsClient:l,apiTimeoutMilliseconds:f,apiMaxRetries:d,apiRetryIntervalMilliseconds:h}),6e4,(function(e){return nm.info("Returning cached response for queues",{cached_queues_length:null==e?void 0:e.length})}))}},jC=function(e,t,n){return function(){if("function"==typeof n&&n(arguments),e&&"function"==typeof e[t])return e[t].apply(e,arguments);throw new ag({cause:Ky.SALEMOVE.NOT_SUPPORTED})}},LC=function(e){if(!k.contains(e[0],og))throw new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"Make sure function argument is one of ISO 3166-1 alpha-2 country codes"})},qC=function(){function e(t){s(this,e),this.triggerQueueMediaSelection=jC(t,"triggerQueueMediaSelection"),this.setChatMessageRenderer=jC(t,"setChatMessageRenderer"),this.setPhoneNumberDefaultCountry=jC(t,"setPhoneNumberDefaultCountry",LC),this.showVisitorCode=jC(t,"showVisitorCode")}return c(e,[{key:"triggerQueueMediaSelection",value:function(e){}},{key:"setChatMessageRenderer",value:function(e){}},{key:"setPhoneNumberDefaultCountry",value:function(e){}},{key:"showVisitorCode",value:function(){}}]),e}(),UC=function e(t){var n=t.id,r=t.siteId,i=t.visitorId,o=t.url,a=t.authenticationApi;s(this,e),this.id=n,this.siteId=r,this.visitorId=i,this.url=o,this.decline=function(e){return a.deleteAuthenticationRequest({id:this.id,siteId:this.siteId,visitorId:this.visitorId,reason:e})}},DC=new ag({cause:Ky.SALEMOVE.NETWORK_TIMEOUT}),VC=function(e){var t=e.wsProxy,n=e.apiTimeoutMilliseconds,r=e.stats,i=Ig({stats:r,protocol:"rest",failureTagProperty:"message",timeout:n,timeoutError:Gv.Observable.throw(DC)});return{createAuthenticationRequest:function(e){var n=(e=Wy(e)).webhooks||[];return i({resource:"authentication-request",method:"create"},(function(){return t.request({method:"POST",url:"".concat(sm.conf.api_url,"/visitor_authentication_requests"),payload:{authentication_provider_id:e.authenticationProviderId,webhooks:n,visitor_id:Jv(),site_id:sm.siteId},headers:ig}).catch((function(t){return function(e,t){var n=404===e.status?new ag({cause:Ky.SALEMOVE.INVALID_INPUT,message:"The authentication provider with ID ".concat(t.authenticationProviderId," was not found.")}):ug(e);return Gv.Observable.throw(n)}(t,e)}))})).toPromise()},deleteAuthenticationRequest:function(e){var n=e.id,r=e.siteId,o=e.visitorId,s=e.reason;return i({resource:"authentication-request",method:"delete"},(function(){return t.request({method:"DELETE",url:"".concat(sm.conf.api_url,"/visitor_authentication_requests/").concat(n),payload:{site_id:r,visitor_id:o,fail_reason:s},headers:ig}).catch(pg,{allowedCauses:[Ky.SALEMOVE.INVALID_INPUT,Ky.SALEMOVE.NETWORK_TIMEOUT]})})).toPromise()}}},FC=!1,BC=function(e){var t=e.volatileChannelObservable,n=e.joinChannel,r=e.renewTokenAndReconnectWaitForTeardown;return function(e,t){return t.switchMap((function(t){return t.observable("message").pipe(eb((function(e){return"engagement.visitor_consolidation.requested"===e.event_type})),Kb((function(n){var r=n.site_id,o=n.visitor_id,s=n.token_event_id;return e("site_visitor:".concat(o),{topics:["site_visitor:".concat(o,":").concat(r)]}).pipe(Rd((function(e){return e&&"unauthorized"===e.error?Ee.empty():Ee.throw(e)})),vb((function(e){return(0,e.observable)("message",{leaveChannelOnDispose:!0})})),eb((function(e){return"engagement.visitor_consolidation"===e.event_type&&e.event_id===s})),$b(1),ub((function(e){return i(i({},e),{},{volatileChannel:t})})))})))}))}(n,t).subscribe((function(e){var t=e.secret,n=e.assumed_visitor_id,i=e.volatileChannel;nm.info("Consolidating visitor",{assumed_visitor_id:n}),i.leave(),r({consolidationSecret:t}).delay(0).subscribe((function(){return Kv(n)}),nm.error.bind(nm,"Error from renewing token and reconnecting in visitor consolidation"))}),nm.error.bind(nm,"Error from visitor consolidation subscription"))},HC=k.pathOr(0,["engagement","unread_message_count"]),WC={MESSAGES:"MESSAGES",UNREAD_MESSAGE_COUNT:"UNREAD_MESSAGE_COUNT"},GC=function(){return A(iA.initialDelay,iA.maxDelay,iA.factor)};function zC(e){var t=e.pubsub,n=e.routingObservable,r=e.getRequestHeaders,o=e.internalVisitorStateObservable,s=new Gv.Subscription,a=Qg(),c=o.map(HC).distinctUntilChanged().publishReplay(1);s.add(c.connect());var u=[];s.add(n.subscribe((function(e){var t=e.queue_ids;u=t})));var l,p=[],f=new Gv.Subject,h=function(e){p=e(p),f.next(p)},d=k.pipe(k.prop("message"),zy({content:"message"}),Hx),b=k.propEq("event_type","queued_message.created"),v=Jv(),m=k.pathEq(["message","sender","type"],"visitor"),y=Gv.Observable.create((function(e){var n=t.joinSiteVisitorNotifications(v,[sm.siteId]).pipe(k.filter(b),k.reject(m),k.map(d)),r=f.subscribe(e);return r.add(n.subscribe((function(e){return h((function(t){return[e].concat(t)}))}))),r})).share(),g=k.propEq("event_type","engagement.files.security_scan_result");a.proxyAll(k.fromPairs([[WC.MESSAGES,y],[WC.UNREAD_MESSAGE_COUNT,c]]));var _=a.addEventListener,w=a.removeEventListener;return{EVENTS:WC,addEventListener:_,uploadFile:function(e,n){var i=n.onUploadProgress,o=Jv();return QI(null,e,{onUploadProgress:i,getRequestHeaders:r},function(e){var n=e.visitorId;return l||((l=t.joinSiteVisitorNotifications(n,[sm.siteId]).filter(g).publishReplay(100)).connect(),l)}({visitorId:o}),sm.conf.communications.allowed_file_content_types).toPromise()},removeEventListener:w,fetchMessages:function(){return new Promise((function(e,t){!function(e){var t=e.getRequestHeaders,n=e.onSuccess,r=e.onError;Ug({url:"".concat(sm.conf.api_url,"/messaging/chat_transcript"),method:"GET",getRequestHeaders:t,responseType:"json",calculateAttemptDelay:GC(),onSuccess:function(e){return n(e.response)},shouldRetry:function(e){return e>=500},onError:r})}({getRequestHeaders:r,onSuccess:function(t){h((function(){return Wx(t).filter(k.identity)})),e(p)},onError:function(e){return t(zI(e))}})}))},send:function(e){var t=e.message,n=e.attachment,o=function(e){var t=e.message,n=e.attachment;return new jx({id:Ey(),content:t,attachment:n,status:jx.prototype.STATUSES.SENDING})}({message:t,attachment:n});return h((function(e){return[o].concat(e)})),new Promise((function(e,s){!function(e){var t=e.id,n=e.message,r=e.attachment,i=e.queueIds,o=e.getRequestHeaders,s=e.onSuccess,a=e.onError;Ug({url:"".concat(sm.conf.api_url,"/messaging/chat_messages/").concat(t),method:"PUT",getRequestHeaders:o,contentType:"application/json",responseType:"json",payload:JSON.stringify({source:"tab",content:n,attachment:r,queue_ids:i}),calculateAttemptDelay:GC(),onSuccess:s,shouldRetry:function(e){return e>=500},onError:a})}({id:o.id,message:t,attachment:n,queueIds:u,getRequestHeaders:r,onSuccess:function(){var t=function(e){return i(i({},e),{},{status:jx.prototype.STATUSES.DELIVERED})}(o);h((function(e){return e.map((function(e){return e.id===o.id?t:e}))})),e(t)},onError:function(e){var t=function(e){return i(i({},e),{},{status:jx.prototype.STATUSES.FAILED})}(o);nm.warn("Failed to send message using message center",{error:e.response||{status:e.status}}),h((function(e){return e.map((function(e){return e.id===o.id?t:e}))})),s(t)}})}))},markMessagesAsRead:function(){return c.take(1).toPromise().then((function(e){if(0!==e)return new Promise((function(e,t){Ug({url:"".concat(sm.conf.api_url,"/messaging/mark_chat_messages_read"),method:"POST",responseType:"json",getRequestHeaders:r,calculateAttemptDelay:GC(),onSuccess:function(){return e()},shouldRetry:function(e){return e>=500},onError:function(e){return t(zI(e))}})}))}))},_stop:function(){s.unsubscribe(),a.stop()}}}var JC=function(e){return function(){console.warn("Private API, do not use"),e.apply(this,arguments)}},QC=function(){function e(t){var n=this,r=t.statusObservable,i=t.cobraObservable,o=t.webRtcMode,a=t.enabledMediaLevel,c=t.statsClient,u=t.channelObservable,l=t.apiStart,p=t.visitorAppPublicInterface,f=t.pubsub,h=t.routingObservable,d=t.visitorMetadata,b=t.internalVisitorStateObservable,v=t.volatileNotifications,m=t.wsProxy,y=t.currentStatusObservable,_=t.operatorPresenceObservable,w=t.getVisitorPriority,E=t.queuesStateUpdatesObservable,O=t.dynamicImport,S=void 0===O?dm:O;s(this,e),this.willNavigate=this.willNavigate.bind(this),this.statsClient=c,this.visitorApp=new qC(p);var T,x=new Gv.ReplaySubject(1);this.setLocale=function(e){if(k.contains(e,k.keys(sm.conf.visitor_app_assets.locales)))return Dg({url:sm.conf.visitor_app_assets.locales[e],retryLimit:5,calculateAttemptDelay:A(1e3),assetKey:"locale-change",identifier:e,onSuccess:function(e){return x.next(e.response)}},this.statsClient),{};throw new ag({cause:this.ERRORS.INVALID_INPUT})},this.messageCenter=new zC({routingObservable:(T={internalVisitorStateObservable:b,pubsub:f,routingObservable:h,getRequestHeaders:this.getRequestHeaders}).routingObservable,getRequestHeaders:T.getRequestHeaders,pubsub:T.pubsub,internalVisitorStateObservable:T.internalVisitorStateObservable});var I=_.map((function(e){return e.values()})),N=_.bufferCount(2,1).flatMap((function(e){var t=g(e,2),n=t[0],r=t[1],i=[];return n.values().forEach((function(e){var t=r.get(e.id);if(t&&!k.equals(e,t))return i.push(t)})),Gv.Observable.from(i)})),C=I,R=bm.vent.observable(bm.MSG.PUBLIC.ENGAGEMENT_START),P=bm.vent.observable(bm.MSG.PUBLIC.ENGAGEMENT_END),M=!1,j=function(e,t){return Gv.Observable.merge(e.map(k.always(!0)),t.map(k.always(!1))).startWith(!1)}(R,P);j.subscribe((function(e){M=e})),this.isInEngagement=function(){return M};var L=new Gv.ReplaySubject(1),q=function(e){var t=k.equals("engagement");return e.map((function(e){var n=e.interaction,r=e.visitor;return new RN({engaged:t(n),name:r&&r.name,email:r&&r.email})}))}(r),U=function(e){return e.connectedObservable.map((function(e){return new PN({connected:e})}))}(f);BC(f);var D=sm.conf.engagement.api_timeout_milliseconds||Xy,V=sm.conf.omniq.api_retry_interval_milliseconds||1e3,F=sm.conf.omniq.api_max_retries||100,B=new LN({wsProxy:m,stats:this.statsClient,apiTimeoutMilliseconds:D}),H=new HN({wsProxy:m,stats:this.statsClient,apiTimeoutMilliseconds:D,visitorMetadata:d,internalVisitorStateObservable:b}),W=new VC({wsProxy:m,apiTimeoutMilliseconds:D,stats:this.statsClient}),G=MC({wsProxy:m,pubsub:f,routingObservable:h,engagementApi:B,engagementRequestApi:H,operatorsObservable:C,cobraObservable:i.pluck("cobraSource"),fetchEngagementDependencies:function(){return S("Comms")},channelObservable:u,communicationLib:sm.conf.communications.lib,statsClient:this.statsClient,apiTimeoutMilliseconds:D,apiRetryIntervalMilliseconds:V,apiMaxRetries:F,connectionStatusObservable:U,webRtcMode:o,enabledMediaLevel:a,visitorMetadata:d,conf:sm.conf,getRequestHeaders:this.getRequestHeaders,internalVisitorStateObservable:b,visitorAuthenticatedExternallyObservable:$v.asObservable().distinctUntilChanged(),volatileNotifications:v,statusObservable:r,queuesStateUpdatesObservable:E});this.queueForEngagement=G.queueForEngagement,this.getQueueWaitDuration=G.fetchWaitDuration,this.getQueues=G.getQueues;var z=G.aggregateQueueStateObservable;this.__queueForEngagement=G.oldQueueForEngagement,this.__setQueueReestablishListener=G.oldSetQueueReestablishListener,this.__fetchQueueWaitDuration=G.getQueueWaitDuration,this.subscribeToQueueStateUpdates=Eg({enabled:sm.conf.omniq.omniq_enabled,statsClient:this.statsClient,pubsub:f}).subscribe,this.requestEngagement=function(e,t){var s=tN({api:H,conf:sm.conf,operatorsObservable:C.take(1),media:e,options:t,statsClient:n.statsClient,cobraObservable:i.take(1).pluck("cobraSource"),channelObservable:u,engagementApi:B,webRtcMode:o,enabledMediaLevel:a,connectionStatusObservable:U,getRequestHeaders:n.getRequestHeaders,internalVisitorStateObservable:b,volatileNotifications:v,statusObservable:r,pubsub:f,wsProxy:m,dynamicImport:S});return function(e){var t=e.operatorObservable,n=e.engagementObservable,r=e.cancelEngagementRequest,i=e.engagementRequestTimeout;return new nN({timeout:i,engagementPromise:n.toPromise(),operatorPromise:t.toPromise(),cancel:r})}({operatorObservable:s.operatorObservable,engagementObservable:s.engagementObservable,cancelEngagementRequest:s.cancelEngagementRequest,engagementRequestTimeout:s.engagementRequestTimeout})};var J=function(e){var t=e.internalVisitorStateObservable,n=e.webRtcMode,r=e.enabledMediaLevel,i=e.engagementRequestApi,o=e.statsClient,s=e.cobraObservable,a=e.channelObservable,c=e.engagementApi,u=e.connectionStatus,l=e.getRequestHeaders,p=e.volatileNotifications,f=e.statusObservable,h=e.pubsub,d=e.wsProxy,b=e.dynamicImport,v=1e3*sm.conf.engagement.proactive_call_timeout,m=k.compose(k.nth(0),k.filter((function(e){return k.any(k.propEq("id",sm.siteId),e.transferrable_sites)})),k.filter(k.propEq("outcome",null)),k.filter(k.propEq("type","proactive")),k.pathOr([],["engagement","requests"]));return t.map(m).filter(k.identity).distinctUntilChanged(null,k.prop("id")).map((function(e){var b=jk({id:e.operator.id,name:e.operator.name,formattedName:e.operator.formatted_name,picture:{url:e.operator.picture_url},mediaType:e.operator.media_type,webRtcMode:n,enabledMediaType:r}),m=jk({id:e.operator.id,name:e.operator.name,formattedName:e.operator.formatted_name,picture:{url:e.operator.picture_url},mediaType:e.offered_media_type,webRtcMode:n,enabledMediaType:r});return{incomingEngagementRequest:gN.create({api:i,id:e.id,operator:b,restrictedOperator:m,message:e.welcome_message,logoUrl:sm.conf.visitor_app.site_logo.url,platform:e.platform,timeout:v,statsClient:o,cobraObservable:s.take(1).pluck("cobraSource"),channelObservable:a,engagementApi:c,connectionStatusObservable:u,getRequestHeaders:l,internalVisitorStateObservable:t,volatileNotifications:p,statusObservable:f,pubsub:h,wsProxy:d}),platform:e.platform}})).switchMap((function(e){var t=e.incomingEngagementRequest,n=e.platform;return b("Comms").mapTo({incomingEngagementRequest:t,platform:n})}))}({dynamicImport:S,internalVisitorStateObservable:b,webRtcMode:o,enabledMediaLevel:a,engagementRequestApi:H,statsClient:this.statsClient,cobraObservable:i,channelObservable:u,engagementApi:B,connectionStatus:U,getRequestHeaders:this.getRequestHeaders,volatileNotifications:v,statusObservable:r,pubsub:f,wsProxy:m}),Q=new rN,Y=J.filter(k.propEq("platform",ng)).map(k.prop("incomingEngagementRequest"));this.setIncomingEngagementRequestHandler=function(e){Q.add(Y.subscribe(e,nm.error))};var K=function(e){var t=e.reestablishObservable,n=e.defaultOmnicoreHandler,r=e.defaultOmnibrowseHandler,i=e.internalVisitorStateObservable,o=e.sessionStore||VT,s=e.timeout||15e3,a=t.publishReplay(1);a.connect();var c={replayedReestablishObservable:a.withLatestFrom(i,(function(e,t){return{source:e,visitorState:t}})).filter((function(e){var t=e.source,n=e.visitorState;return!!t.engagement.engagementId&&k.compose(k.find(k.propEq("id",t.engagement.engagementId)),k.pathOr([],["engagement","engagements"]))(n)})).map((function(e){return e.source})),sessionStore:o,timeout:s};return{setOmnicoreReestablishHandler:CN(k.merge(c,{defaultHandler:n,storeKey:"custom_reestablish_handler_set",platform:ng})),setOmnibrowseReestablishHandler:CN(k.merge(c,{defaultHandler:r,storeKey:"omnibrowse_custom_reestablish_handler_set",platform:rg}))}}({reestablishObservable:l.flatMap((function(){return NN({channelObservable:u,internalVisitorStateObservable:b,statusObservable:r,webRtcMode:o,enabledMediaLevel:a,statsClient:n.statsClient,cobraObservable:i,isEngagedObservable:j,engagementApi:B,connectionStatusObservable:U,getRequestHeaders:n.getRequestHeaders,volatileNotifications:v,pubsub:f,wsProxy:m,dynamicImport:S})})),defaultOmnicoreHandler:function(e){return nm.warn("Engagement reestablished without a reestablish handler in place")},defaultOmnibrowseHandler:function(e){return nm.warn("Phone-first (OmniBrowse) engagement reestablished without a reestablish handler in place")},internalVisitorStateObservable:b}),X=K.setOmnicoreReestablishHandler,$=K.setOmnibrowseReestablishHandler;this.setEngagementReestablishHandler=X,this.requestAsset=function(e,t){t||(t={});return yN(e,(function(){return k.merge(n.getRequestHeaders(),t)})).toPromise()},this.omnibrowse=new oN({incomingEngagementRequestObservable:J,setOmnibrowseReestablishHandler:$,statsClient:this.statsClient,wsProxy:m}),this.overseer=new pN({operatorListReady:I.take(1),isOmniqEnabled:sm.conf.omniq.omniq_enabled,routingObservable:h,queueStateReady:z.take(1)}),this.omnicall=new hN,this.config=new vN,this.getBrowserContext=function(){return y.take(1).map((function(e){return{tab_id:sm.tabId,url:window.location.href,metadata:sm.conf.visitor_metadata,status:e}})).toPromise()},this.updateInformation=function(e){return y.take(1).flatMap((function(t){return KN(e,{createApiRequestObservable:function(e){return qg({url:xx("/sites/".concat(Xv(),"/visitors/").concat(Jv())),method:"PATCH",contentType:"application/json",payload:e})},serverResponseTimeout:Xy,tabId:sm.tabId,visitorMetadata:sm.conf.visitor_metadata,status:t})})).toPromise()},this.createAuthenticationRequest=function(e){return nm.info("Create authentication request called",e),W.createAuthenticationRequest(e)},this.setupContactOperatorButton=function(e){return e||(e={}),nm.warn("setupContactOperatorButton is deprecated!"),L.next(e)};var Z=function(e){var t=e.internalVisitorStateObservable,n=e.authenticationApi,r=k.compose(k.find((function(e){return e.site_id===Xv()&&e.visitor_id===Jv()})),k.pathOr([],["authentication_requests"]));return t.map(r).filter(k.identity).distinctUntilChanged(k.equals).map((function(e){return k.construct(UC)({id:e.id,siteId:e.site_id,visitorId:e.visitor_id,url:e.url,authenticationApi:n})}))}({internalVisitorStateObservable:b,authenticationApi:W}),ee=k.fromPairs([[this.EVENTS.ENGAGEMENT_START,R],[this.EVENTS.ENGAGEMENT_END,P],[this.EVENTS.VISITOR_STATUS_UPDATE,q],[this.EVENTS.OPERATOR_STATUS_UPDATE,N],[this.EVENTS.OPERATOR_LIST_UPDATE,I],[this.EVENTS.ENGAGEMENT_REQUEST,J.map(k.always({}))],[this.EVENTS.CONNECTION_STATUS_UPDATE,U],[this.EVENTS.QUEUE_STATE_UPDATE,z],[this.EVENTS.AUTHENTICATION_REQUEST,Z],["contact_operator_button_configuration",L],["locale_change_requested",x]]),te=Qg();te.proxyAll(ee),this.addEventListener=te.addEventListener,this.removeEventListener=te.removeEventListener,this.observable=function(e){return ee[e]},function(e){var t,n=e.internalVisitorStateObservable,r=e.useOmniq,i=e.operatorListUpdate,o=e.queueStateUpdate,s=e.statsClient,a=e.staffingCheckDelayMs,c=void 0===a?1e4:a,u=e.recordingMaxTime,l=void 0===u?6e4:u,p=k.compose(k.length,k.filter(k.path(["state","available"]))),f=n.map((function(e){return Boolean(SN(e))})).filter(k.equals(!0));t=r?o.map((function(e){return sm.conf.visitor_api.enable_staffing_logs&&nm.info("[staffing-logs] Recording queue state",{queue_state:e.state}),k.contains(e.state,[e.QUEUE_STATES.CAN_QUEUE,e.QUEUE_STATES.QUEUED])?"staffed":"general"})):i.map((function(e){return sm.conf.visitor_api.enable_staffing_logs&&nm.info("[staffing-logs] Recording operator state",{operator_count:p(e)}),p(e)>0?"staffed":"general"})),sm.conf.visitor_api.enable_staffing_logs&&nm.info("[staffing-logs] Starting recorder timer",{duration:c});var h=Gv.Observable.create((function(e){var t=setTimeout((function(){e.next(null)}),c);return function(){return clearTimeout(t)}})),d=new Date,b=function(){return window.performance&&window.performance.now&&window.performance.now()},v=b();h.flatMapTo(t).take(1).takeUntil(f).subscribe((function(e){var t=new Date,n=b(),r=t-d+1e3<=c;r||t-d>l?nm.warn("Recording staffing failed due to browser timer issues",{type:e,early_recording:r,start_time:d.toISOString(),recording_time:t.toISOString(),accurate_start_time:v,accurate_recording_time:n,difference:t&&t-d,accurate_difference:n&&n-v}):s.increment("usage_metrics.visitor.reactive_tab_showed",["type:".concat(e),"source:desktop","site_id:".concat(Xv()),"visitor_id:".concat(Jv())])}),nm.error)}({internalVisitorStateObservable:b,useOmniq:sm.conf.omniq.omniq_enabled,operatorListUpdate:this.observable(this.EVENTS.OPERATOR_LIST_UPDATE),queueStateUpdate:this.observable(this.EVENTS.QUEUE_STATE_UPDATE),statsClient:this.statsClient});var ne=Ay();!function(e){var t=e.visitorIdleAfterTime,n=e.pubsub;t.subscribe((function(){sm.logger.info("Visitor was idle for too long, disconnecting"),n.disconnect(),FC=!0}))}({visitorIdleAfterTime:function(e,t){var n=e.activityObservable,r=e.engagementEndObservable,i=e.timeUntilIdle,o=e.maxIdleTime,s=e.isEngaged;return Gv.Observable.merge(n,r).debounceTime(i+o,t).filter((function(){return!s()})).map((function(){}))}({activityObservable:ne,engagementEndObservable:P,timeUntilIdle:1e3*sm.conf.engagement.visitor_time_to_inactive_sec,maxIdleTime:1e3*sm.conf.visitor_api.max_idle_time_seconds,isEngaged:function(){return M}}).filter((function(){return sm.conf.visitor_api.disconnect_idle_visitors})),pubsub:f}),function(e){var t=e.activityObservable,n=e.pubsub;t.filter((function(){return FC&&n.allowReconnection()})).subscribe((function(){sm.logger.info("Reconnecting idle visitor due to detected activity"),FC=!1,n.connect()}))}({activityObservable:ne,pubsub:f}),this.getSessionContext=function(){var e={tab_id:sm.tabId,visitor_priority:w(),access_token:sm.accessToken};return encodeURIComponent(btoa(JSON.stringify(e)))},this.__pubsub__={reconnect:JC(f.reconnect)}}return c(e,[{key:"getRequestHeaders",value:function(){return{Accept:"application/vnd.salemove.v1+json",Authorization:"Bearer "+sm.accessToken}}},{key:"getVisitorId",value:function(){return Jv()}},{key:"getSiteId",value:function(){return Xv()}},{key:"leaveMessage",value:function(e){return mN(e,{createApiRequestObservable:function(e){return qg({url:xx("/visitor/offline_message"),method:"POST",contentType:"application/json",payload:e})},serverResponseTimeout:Xy}).toPromise()}},{key:"leaveOperatorMessage",value:function(e){return function(e,t,n){e||(e={}),n||(n=Gv.Scheduler.asap);var r=e.operatorId;return r?mN(k.merge({operator_id:r},e),t,["operator_id"],n):Gv.Observable.throw({cause:Ky.SALEMOVE.INVALID_INPUT,message:"operatorId must be specified"})}(e,{createApiRequestObservable:function(e){return qg({url:xx("/visitor/operator_message"),method:"POST",contentType:"application/json",payload:e})},serverResponseTimeout:Xy}).toPromise()}},{key:"willNavigate",value:function(){return Promise.resolve({})}},{key:"changeElementAttributesForCobrowsing",value:function(e,t){if("function"!=typeof t)throw new ag({cause:this.ERRORS.INVALID_INPUT});return e.sm_change_element_attributes=zg("Custom element attribute serializer threw error",tg,t),function(e){e.setAttribute(MN,"0"===(e.getAttribute(MN)||"0")?"1":"0")}(e),null}}]),e}();QC.prototype.ERRORS={INVALID_INPUT:"invalid input",OPERATOR_UNAVAILABLE:"operator unavailable",INTERNAL_ERROR:"internal error",RESOURCE_NOT_FOUND:"not found",OPERATOR_DECLINED:"operator declined",DECLINE:"decline",CANCEL:"cancel",TIMEOUT:"timeout",NETWORK_TIMEOUT:"network timeout",CONNECTION_LOST:"connection lost",TOO_MANY_REQUESTS:"too many requests",FORBIDDEN:"forbidden",NOT_SUPPORTED:"not supported",DISABLED:"disabled",ALREADY_QUEUED:"already queued",ALREADY_ENGAGED:"already engaged",CONFLICT:"conflict",FILE_TOO_LARGE:"file too large",FILE_CONTENT_TYPE_NOT_ALLOWED:"file content type not allowed"},QC.prototype.EVENTS={ENGAGEMENT_END:"sm:engagement:end",ENGAGEMENT_START:"sm:engagement:start",VISITOR_STATUS_UPDATE:"sm:visitor_status:update",ENGAGEMENT_REQUEST:"sm:engagement:request",OPERATOR_LIST_UPDATE:"sm:operator_list:update",OPERATOR_STATUS_UPDATE:"sm:operator_status:update",CONNECTION_STATUS_UPDATE:"sm:connection_status:update",QUEUE_STATE_UPDATE:"sm:queue:update",AUTHENTICATION_REQUEST:"sm:authentication:request"};var YC="sm.app.visitor_api.send_capabilities",KC=function(){function e(t){var n=t.channelObservable,r=t.statsClient,i=t.getLocalCapabilities,o=void 0===i?BI:i;s(this,e),this.channelObservable=n,this.statsClient=r,this.getLocalCapabilities=o,this._receivePostMessage=this._receivePostMessage.bind(this),this._restoreLastUrl=this._restoreLastUrl.bind(this),this._subscription=new Gv.Subscription,this.lastUrl=window.location.href}return c(e,[{key:"start",value:function(){return this._addListeners()}},{key:"capabilitiesRequestObservable",value:function(){return this.channelObservable.switchMap((function(e){var t=e.channel;return function(e){return sm.logger.log("Capabilities response, received request"),e.observable("capabilities:request")}(t).map((function(){return t}))}))}},{key:"_addListeners",value:function(){var e=this;bm.vent.observable("visit:restore_url").subscribe(this._restoreLastUrl,sm.logger.error),window.addEventListener("message",this._receivePostMessage,!1),this._subscription.add(this.capabilitiesRequestObservable().map((function(t){return{channel:t,localCapabilities:e.getLocalCapabilities()}})).do((function(){return e.statsClient.increment(YC,["action:succeeded"])})).do(null,(function(){return e.statsClient.increment(YC,["action:failed"])})).subscribe((function(e){var t=e.channel,n=e.localCapabilities;sm.logger.log("Sending local capabilities",n),t.emit("capabilities:response",n)}),sm.logger.warn.bind(sm.logger,"Failed to send visitor capabilities")))}},{key:"_receivePostMessage",value:function(e){try{var t=JSON.parse(e.data);t["sm-xdr-url"]&&(this.lastUrl=t["sm-xdr-url"])}catch(e){}}},{key:"_restoreLastUrl",value:function(){this.lastUrl&&this.lastUrl.split("#")===window.location.href.split("#")[0]?window.location.reload():window.location.href=this.lastUrl}}]),e}(),XC=["v1"],$C=new Promise((function(e,t){return sm._apiHandlers.push({resolve:e,options:{version:"v1"}})})),ZC=new Gv.Subject,eR=Gv.Observable.fromPromise($C).flatMap((function(e){return Gv.Observable.merge(e.observable(e.EVENTS.ENGAGEMENT_START),e.observable(e.EVENTS.ENGAGEMENT_END).map((function(){return null})))})).publishReplay(1);eR.connect();var tR=function(){function e(t){var n=t.element;s(this,e),this._empty=this._empty.bind(this),this._startOperatorMediaInElement=this._startOperatorMediaInElement.bind(this),this.element=n,this._subscription=new Gv.Subscription;var r=g(eR.partition(k.identity),2);this.startMediaObservable=r[0],this.endMediaObservable=r[1]}return c(e,[{key:"start",value:function(){this._subscription.add(this.startMediaObservable.subscribe(this._startOperatorMediaInElement,nm.error)),this._subscription.add(this.endMediaObservable.subscribe(this._empty,nm.error))}},{key:"destroy",value:function(){this._subscription.unsubscribe()}},{key:"_empty",value:function(){this.element.innerHTML=""}},{key:"_startOperatorMediaInElement",value:function(e){var t=n.default.visitor_api?n.default.visitor_api.use_updated_webcomponents:void 0;e.communicationWidget.startOperatorMedia(this.element),nm.info("Starting operator media in widget",{engagement_id:e.engagementId,updated_webcomponents:t}),rm.increment("sm.app.visitor.customElements",["action:succeeded","type:engaged_operator","updated_webcomponents:".concat(t)])}}]),e}(),nR=function(){if(sm.conf.visitor_api&&sm.conf.visitor_api.use_updated_webcomponents)return function(e){l(n,e);var t=m(n);function n(){return s(this,n),t.apply(this,arguments)}return c(n,[{key:"connectedCallback",value:function(){return this._controller=new tR({element:this}),this._controller.start()}},{key:"disconnectedCallback",value:function(){return this._controller.destroy()}}]),n}(b(HTMLElement));if(window.customElements){var e=function e(){return window.Reflect.construct(HTMLElement,[],e)};return Object.setPrototypeOf(e.prototype,HTMLElement.prototype),Object.setPrototypeOf(e,HTMLElement),e.prototype.connectedCallback=function(){return this._controller=new tR({element:this}),this._controller.start()},e.prototype.disconnectedCallback=function(){return this._controller.destroy()},e}var t={}.hasOwnProperty;return function(e){function n(){return n.__super__.constructor.apply(this,arguments)}return function(e,n){var r;for(r in n)t.call(n,r)&&(e[r]=n[r]);function i(){this.constructor=e}i.prototype=n.prototype,e.prototype=new i,e.__super__=n.prototype}(n,HTMLElement),n.prototype.attachedCallback=function(){return this._controller=new tR({element:this}),this._controller.start()},n.prototype.detachedCallback=function(){return this._controller.destroy()},n}()},rR=function(){var e=nR();if(window.customElements)try{customElements.get("sm-engaged-operator")||window.customElements.define("sm-engaged-operator",e)}catch(e){var t=n.default.visitor_api?n.default.visitor_api.use_updated_webcomponents:void 0;rm.increment("sm.app.visitor.customElements",["action:failed","type:engaged_operator","updated_webcomponents:".concat(t)]),nm.error("Failed to initiate sm-engaged-operator",{error_message:e?e.message:void 0,updated_webcomponents:t})}else document.registerElement("sm-engaged-operator",e)},iR=function(){function e(t){var n=t.engagedVisitorElement;s(this,e),this._addListeners=this._addListeners.bind(this),this._empty=this._empty.bind(this),this._startVisitorMedia=this._startVisitorMedia.bind(this),this.engagedVisitorElement=n,this._subscription=new Gv.Subscription}return c(e,[{key:"start",value:function(){return this._addListeners()}},{key:"destroy",value:function(){return this._subscription.unsubscribe()}},{key:"_addListeners",value:function(){var e=g(eR.partition(k.identity),2),t=e[0],n=e[1];return this._subscription.add(t.subscribe(this._startVisitorMedia,nm.error)),this._subscription.add(n.subscribe(this._empty,nm.error))}},{key:"_empty",value:function(){this.engagedVisitorElement.innerHTML=""}},{key:"_startVisitorMedia",value:function(e){var t=n.default.visitor_api?n.default.visitor_api.use_updated_webcomponents:void 0,r=document.createElement("div");this.engagedVisitorElement.appendChild(r),e.communicationWidget.startVisitorMedia(r),nm.info("Starting visitor media in widget",{engagement_id:e.engagementId,updated_webcomponents:t}),rm.increment("sm.app.visitor.customElements",["action:succeeded","type:engaged_visitor","updated_webcomponents:".concat(t)])}}]),e}(),oR=function(){if(sm.conf.visitor_api&&sm.conf.visitor_api.use_updated_webcomponents)return function(e){l(n,e);var t=m(n);function n(){return s(this,n),t.apply(this,arguments)}return c(n,[{key:"connectedCallback",value:function(){this._controller=new iR({engagedVisitorElement:this}),this._controller.start()}},{key:"disconnectedCallback",value:function(){this._controller.destroy()}}]),n}(b(HTMLElement));if(window.customElements){var e=function e(){return window.Reflect.construct(HTMLElement,[],e)};return Object.setPrototypeOf(e.prototype,HTMLElement.prototype),Object.setPrototypeOf(e,HTMLElement),e.prototype.connectedCallback=function(){this._controller=new iR({engagedVisitorElement:this}),this._controller.start()},e.prototype.disconnectedCallback=function(){this._controller.destroy()},e}var t={}.hasOwnProperty;return function(e){function n(){return n.__super__.constructor.apply(this,arguments)}return function(e,n){var r;for(r in n)t.call(n,r)&&(e[r]=n[r]);function i(){this.constructor=e}i.prototype=n.prototype,e.prototype=new i,e.__super__=n.prototype}(n,HTMLElement),n.prototype.attachedCallback=function(){return this._controller=new iR({engagedVisitorElement:this}),this._controller.start()},n.prototype.detachedCallback=function(){return this._controller.destroy()},n}()},sR=function(){var e=oR();if(window.customElements)try{customElements.get("sm-engaged-visitor")||window.customElements.define("sm-engaged-visitor",e)}catch(e){var t=n.default.visitor_api?n.default.visitor_api.use_updated_webcomponents:void 0;rm.increment("sm.app.visitor.customElements",["action:failed","type:engaged_visitor","updated_webcomponents:".concat(t)]),nm.error("Failed to initiate sm-engaged-visitor",{error_message:e?e.message:void 0,updated_webcomponents:t})}else document.registerElement("sm-engaged-visitor",e)},aR=!1,cR=!1,uR=[],lR=function e(){if(!cR){if(!document.body)return setTimeout(e,13);if(cR=!0,uR){for(var t,n=0;t=uR[n++];)t.call(document);uR=null}}},pR=function e(){document.removeEventListener("DOMContentLoaded",e,!1),lR()};function fR(e){!function(){if(!aR){if(aR=!0,"complete"===document.readyState||"interactive"===document.readyState)return lR();document.addEventListener("DOMContentLoaded",pR,!1),window.addEventListener("load",lR,!1)}}(),cR?e.call(document):uR&&uR.push(e)}sm.ready=fR;var hR=function(e){localStorage.setItem("sm.access_token",e)};if(sm.conf.visitor_api.persist_visitor_session_in_url){sm.urlParams=rx({accessToken:/.+/,tabId:/.+/},{targetWindow:window,logger:nm})}else sm.urlParams={};if("show_visitor_code"===sm.conf.visitor_app.chat_link_visitor_consolidation){var dR=rx({showVisitorCode:/true/},{targetWindow:window,logger:nm});k.isEmpty(dR)||(sm.urlParams.showVisitorCode=!0)}var bR={setStatsClient:function(){},setLogger:function(){},ready:function(){}},vR=function(e){var t=sm.conf.visitor_app_assets,n="visitor_app";return new Promise((function(r,i){var o,s,a;-1!==["latest_new_app","latest_v2","latest_v2_plus"].indexOf(sm.conf.visitor_app_option)?(o=function(e){e.setAttribute("data-sm-visitor-app-asset",""),e.setAttribute("data-loaded-callback","sm.visitorAppLoaded"),sm.visitorAppLoaded=r},a=null):(o=function(e){return e.setAttribute("data-sm-visitor-app-asset","")},a=function(){return r(bR)}),t.js.forEach((function(t){s=t.substring(t.lastIndexOf("/")+1),P({integrity:R({versionedName:s}),fileUrl:t,beforeLoad:o,onAttempt:function(){e.increment("sm.assets.load",["action:attempted","asset:".concat(n,".js")])},onLoad:function(){e.increment("sm.assets.load",["action:succeeded","asset:".concat(n,".js")]),a&&a()},onError:function(){e.increment("sm.assets.load",["action:warning","asset:".concat(n,".js")])},onGiveUp:function(){e.increment("sm.assets.load",["action:failed","asset:".concat(n,".js")]),nm.warn(new Error("Failed to load visitor app JS asset"),{asset_url:t})}})})),t.css.forEach((function(t){var r,i,o,a,c,u;s=t.substring(t.lastIndexOf("/")+1),r={integrity:R({versionedName:s}),fileUrl:t,onAttempt:function(){e.increment("sm.assets.load",["action:attempted","asset:".concat(n,".css")])},onError:function(){e.increment("sm.assets.load",["action:warning","asset:".concat(n,".css")])},onGiveUp:function(){e.increment("sm.assets.load",["action:failed","asset:".concat(n,".css")]),nm.warn(new Error("Failed to load visitor app CSS asset"),{asset_url:t})}},i=r.integrity,o=r.fileUrl,a=r.onAttempt,c=r.onError,u=r.onGiveUp,N({calculateAttemptDelay:A(1e3),attempt:function(e){var t=e.repeat;"function"==typeof a&&a();var n=document.createElement("link");return n.type="text/css",n.rel="stylesheet",n.onerror=function(){"function"==typeof c&&c(),document.head.removeChild(n),t()},n.href=o,i&&(n.setAttribute("integrity",i),n.setAttribute("crossorigin","*")),document.head.appendChild(n),n},onGiveUp:function(){"function"==typeof u&&u()},retryLimit:5})}))}))},mR=function(){return-1!==["latest_new_app","latest_v2","latest_v2_plus","custom","omnibrowse"].indexOf(sm.conf.visitor_app_option)},yR=function(e){var t=e.stats;return mR()?vR(t):Promise.resolve(bR)},gR=function(){return sm.conf.visitor_app.visitor_app_default_locale||""},_R={translations:{}},wR=function(e){return new Promise((function(t,n){var r=gR(),i=(sm.conf.visitor_app_assets.locales||{})[r];i?Dg({url:i,retryLimit:5,calculateAttemptDelay:A(1e3),assetKey:"locale",identifier:r,onSuccess:function(e){t({translations:e.response})},onError:function(){nm.warn("Fetching locale failed, using empty locale"),t(_R)}},e):(e.increment("sm.assets.load",["action:failed","asset:locale","reason:locale_missing"]),nm.warn("Locale is not present, starting with defaultMessages",{localeKey:r,localeUrl:i}),t(_R))}))},ER=function(e){return"en-US"===gR()?Promise.resolve(_R):mR()?wR(e):Promise.resolve(_R)},OR=function(e){var t=Jk.extractLinkFromEvent(e);t&&function(e,t){"https:"!==t.protocol&&"http:"!==t.protocol||Jk.isAllowedToNavigate(t.hostname)||(e.preventDefault(),window.open(t.href))}(e,t)},SR=function(){return qT.unloadMaybeToPageCache.subscribe((function(){return VT.set(Ex,Sx(document))}))},TR=function(e){var t=e.getAccessToken,n=e.stats,r=e.pubsub,i=e.visitorPresenceChannel,o=e.internalVisitorStateObservable,s=e.volatileNotifications,a=e.wsProxy,c=e.operatorPresenceObservable,u=e.routingObservable;document.body.addEventListener("click",OR),SR(),function(e){var t=e.getAccessToken,n=e.stats,r=e.pubsub,i=e.visitorPresenceChannel,o=e.internalVisitorStateObservable,s=e.volatileNotifications,a=e.wsProxy,c=e.operatorPresenceObservable,u=e.routingObservable;l_();var l=Zg({channelObservable:yx({internalVisitorStateObservable:o,getAccessToken:t,stats:n,visitorPresenceChannel:i,salemovePresentInParent:!0}).channelObservable,logger:nm}).cobraObservable,p=Eg({enabled:sm.conf.omniq.omniq_enabled,statsClient:n,pubsub:r});Gg({internalVisitorStateObservable:o,cobraObservable:l,volatileNotifications:s,stats:n,wsProxy:a,currentStatusObservable:HT(o),operatorPresenceObservable:c,queuesStateUpdatesObservable:p,routingObservable:u})}({getAccessToken:t,stats:n,pubsub:r,visitorPresenceChannel:i,internalVisitorStateObservable:o,volatileNotifications:s,wsProxy:a,operatorPresenceObservable:c,routingObservable:u}),_m(),Qk()},kR={setup:function(){hR(sm.accessToken),nm.info("Visitor WebRTC mode",{webrtc_mode:Ek()}),sm.conf.visitor_app.theme=sm.conf.visitor_app.theme.desktop_css_url;var e=Zk(),t=e.bestEffortXDomainStorage,n=e.windowNameStorage,r=e.xDomainUrlStorage,i=FT.setup(n,{sessionContext:sm._sessionContext,tabIdFromConfiguration:sm.tabId}).getId();sm.tabId=i;var o=new Gv.Subject;!function(e,t){x=k.merge(x,{enabled:t}),e.take(1).subscribe((function(e){e.volatileChannelObservable.flatMap((function(e){return e.observable("system:visitor_retry_configuration")})).subscribe((function(e){x=e}))}))}(o,sm.conf.visitor_request_retries_enabled);var s=function(e){return e.getItem(zT)}(t)||GT,a=function(){return s},c=k.pathOr(!1,["sm","conf","site_visitor_config","detect_visitor_by_external_session_token"])(window),u=k.pathOr(!1,["sm","conf","site_visitor_config","opaque_visitor_authentication_enabled"])(window),l=new Gv.Subject,p=function(e){var t=e.fetchToken,n=void 0===t?rk:t,r=e.accessToken,i=e.scheduler,o=void 0===i?Gv.Scheduler.asap:i,s=e.accessTokenRenewalSignal,a=void 0===s?Gv.Observable.empty():s,c=e.backoffStrategy,u=void 0===c?A:c,l=e.getVisitorPriority,p=e.getVisitorTabId,f=void 0===p?function(){return sm.tabId}:p,h=e.detectVisitorByExternalSessionTokenEnabled,d=void 0!==h&&h,b=e.opaqueVisitorAuthenticationEnabled,v=void 0!==b&&b,m=new Gv.ReplaySubject(1),y=tk(r);m.next(y);var g=u(3e3),_=function(e){return function(e){return e&&e.consolidationSecret}(e)||function(e){return e&&e.newIdToken}(e)};return m.switchMap((function(e){return Gv.Observable.timer(e,o)})).merge(a.filter(k.complement(_))).throttleTime(6e4,o).merge(a.filter(_)).switchMap((function(e){var t={priority:l(),tabId:f(),detectVisitorByExternalSessionTokenEnabled:d,opaqueVisitorAuthenticationEnabled:v};e&&e.consolidationSecret?t.consolidationSecret=e.consolidationSecret:t.accessToken=r,nm.info("Refreshing access token");var i=Gv.Observable.defer((function(){return n(t)})).do(null,(function(e){503!==e.status&&429!==e.status||(nm.warn("Visitor access token unavailable, switching to maximum backoff"),g.maximizeNextDelay()),nm.warn("Failed to fetch JWT token. Retrying...",e.responseText)}));return ry(i,{maxRetries:403200,calculateDelay:g,scheduler:o}).do((function(e){var t=e.accessToken;r=t;var n=tk(t);m.next(n),nm.info("Access token refresh succeeded",{interval_seconds:n/1e3})}))}))}({accessToken:sm.accessToken,accessTokenRenewalSignal:l,getVisitorPriority:a,detectVisitorByExternalSessionTokenEnabled:c,opaqueVisitorAuthenticationEnabled:u}).share(),f=function(){return sm.accessToken},h=ew({server:sm.conf.pubsub_server,stats:rm,logsEnabled:sm.conf.visitor_api.pubsub_logs_enabled,getAccessToken:f,renewAccessToken:function(e){return l.next(e),p.delay(1e3)},reconnectConf:{initialDelay:sm.conf.visitor_api.socket_connection_error_retry_delay,maxDelay:sm.conf.visitor_api.socket_connection_error_max_delay,delayFactor:sm.conf.visitor_api.socket_connection_error_delay_factor},getVisitorPriority:a});o.next(h),p.subscribe((function(e){var t,n,r,i,o,s=e.accessToken,a=e.visitorId,c=e.authenticatedExternally;(sm.accessToken=s,hR(s),u)&&(t={oldVisitorId:Jv(),newVisitorId:a,oldAuthenticatedExternally:$v.value,newAuthenticatedExternally:c},n=t.oldVisitorId,r=t.newVisitorId,i=t.oldAuthenticatedExternally,o=t.newAuthenticatedExternally,r!==n&&o!==i&&function(e){var t=e.visitorId,n=e.authenticatedExternally,r=e.pubsub,i=e.setNewVisitorIdFn,o=void 0===i?Kv:i,s=e.setVisitorAuthenticatedExternallyFn;(void 0===s?Zv:s)(n),r.reconnect(),o(t)}({visitorId:a,authenticatedExternally:c,pubsub:h}))})),u&&ek().switchMap((function(e){var t=e.idToken;return function(e){var t=e.accessTokenObservable,n=e.timeInterval,r=void 0===n?1e3:n,i=e.scheduler,o=void 0===i?Gv.Scheduler.asap:i,s=e.initialValue,a=e.getGliaContextAsObservable,c=void 0===a?ek:a,u=s;return Gv.Observable.merge(t,Gv.Observable.of(null)).switchMap((function(){return Gv.Observable.timer(r,r,o).switchMap((function(){return c().filter((function(e){var t=e.idToken,n=t===u;return u=t,!n}))})).take(1)}))}({accessTokenObservable:p,initialValue:t})})).subscribe((function(){l.next({newIdToken:!0})}));var d=new tw(h,{tabId:sm.tabId,idleTimeoutSeconds:sm.conf.engagement.visitor_time_to_inactive_sec,visitorMetadata:sm.conf.visitor_metadata}),b=RT({pubsub:h,tabId:sm.tabId});(function(e,t){return e.map(KT).distinctUntilChanged().do((function(e){return t.setItem(zT,e)}))})(b,t).subscribe((function(e){s=e}));var v,m=h.volatileChannelObservable.flatMap((function(e){return(0,e.observable)("message")})),y=function(e){var t=e.pubsub,n=t.joinChannel("websocket_proxy").publishReplay(1);return n.connect(),{connectedObservable:t.connectedObservable,request:function(e,t){return t||(t={}),"GET"===e.method&&null!==e.payload?(PT.error("Request with GET method cannot have payload",{params:e}),Gv.Observable.throw("Request with GET method cannot have payload")):n.flatMap((function(n){return n.push("request",e,t)})).flatMap(MT).catch(jT)}}}({pubsub:h});v=sm.conf.visitor_api.use_updated_webcomponents?window.customElements&&window.customElements.define?"webcomponents_es5":"webcomponents":"legacy_webcomponents";var g=sm.BusinessRules.Controller.actionTriggers(m,sm.BusinessRules.ACTION_TYPES.SHOW_OPERATORS_IN_SELECTOR_V2).scan((function(e,t){var n=t.operator_team_id,r=t.rule_id,i=t.rule_name,o=t.clear_previous;return o?{team_ids:[n],rule_id:r,rule_name:i,clear_previous:o}:{team_ids:k.union(e.team_ids,[n]),rule_id:r,rule_name:i,clear_previous:o}}),{}).do((function(e){return nm.info("Business rule setting visible teams",{team_ids:e.team_ids,rule_id:e.rule_id,rule_name:e.rule_name,clear_previous:e.clear_previous})})).pluck("team_ids").publishReplay(1);g.connect();var _=function(e){var t=e.pubsub,n=e.visibleTeamsObservable,r=e.enabledMediaLevel,i=e.webRtcMode,o=t.joinChannel("site_operator_presence:".concat(sm.siteId)).map((function(e){var t=e.phoenixChannel;return new U_(t)})).switchMap((function(e){return Gv.Observable.create((function(t){return Uk({presence:e,presenceMapper:Lk({enabledMediaLevel:r,webRtcMode:i}),visibleTeamsObservable:n,onChange:function(e){return t.next(e)}})}))})).publishReplay(1);return(o=ny(o)).sampleTime(300)}({pubsub:h,visibleTeamsObservable:g,enabledMediaLevel:sm.conf.communications.enabled_media_level,webRtcMode:Ek()}),w=sm.conf.engagement.default_queues||[],E=ex({internalVisitorStateObservable:b,defaultQueues:w});dm(v).subscribe((function(){fR((function(){window!==window.top?kR.setupIFrame({getAccessToken:f,stats:rm,pubsub:h,visitorPresenceChannel:d,internalVisitorStateObservable:b,volatileNotifications:m,wsProxy:y,bestEffortXDomainStorage:t,operatorPresenceObservable:_,xDomainUrlStorage:r,getVisitorPriority:a,routingObservable:E,tabId:i}):(sm.visitorPageNotifierSubscription={unsubscribe:a_()},c_(),kR.setupApp({getAccessToken:f,stats:rm,pubsub:h,visitorPresenceChannel:d,internalVisitorStateObservable:b,volatileNotifications:m,wsProxy:y,operatorPresenceObservable:_,bestEffortXDomainStorage:t,xDomainUrlStorage:r,getVisitorPriority:a,routingObservable:E}))}))}))},setupApp:function(e){var t=e.getAccessToken,n=e.stats,r=e.pubsub,i=e.visitorPresenceChannel,o=e.internalVisitorStateObservable,s=e.volatileNotifications,a=e.wsProxy,c=e.operatorPresenceObservable,u=e.xDomainUrlStorage,l=e.getVisitorPriority,p=e.routingObservable;rR(),sR();return Promise.all([yR({stats:n}),ER(n),nx({stats:n})]).then((function(e){return"[0]"!==JSON.stringify([0])?(r.disconnect(),Promise.reject('Misimplemented array stringification: (JSON.stringify([0]) !== "[0]"')):e})).then((function(e){var t=g(e,2);return function(e){var t=e.visitorApp,r=e.locale;return void 0===t.setStatsClient&&nm.warn("Setting dependencies failed. visitorApp.setStatsClient was undefined.",{visitorApp:t}),t.setStatsClient(n),t.setLogger(nm),t.ready({locale:r}),t}({visitorApp:t[0],locale:t[1]})})).then((function(e){u.setItem("tabId",sm.tabId),u.setItem("accessToken",sm.accessToken);var f=function(e){var t=e.getAccessToken,n=e.stats,r=e.visitorPresenceChannel,i=e.internalVisitorStateObservable;l_();var o=yx({internalVisitorStateObservable:i,getAccessToken:t,stats:n,visitorPresenceChannel:r,salemovePresentInParent:!1}),s=o.channelObservable;return{channelObservable:s,statusObservable:o.statusObservable,cobraObservable:Zg({channelObservable:s,logger:nm}).cobraObservable}}({getAccessToken:t,stats:n,pubsub:r,visitorPresenceChannel:i,internalVisitorStateObservable:o}),h=HT(o),d=Eg({enabled:sm.conf.omniq.omniq_enabled,statsClient:n,pubsub:r});!function(e){var t,n=e.statusObservable,r=e.cobraObservable,i=e.statsClient,o=e.channelObservable,s=e.visitorAppPublicInterface,a=e.pubsub,c=e.visitorMetadata,u=e.internalVisitorStateObservable,l=e.routingObservable,p=e.volatileNotifications,f=e.wsProxy,h=e.currentStatusObservable,d=e.operatorPresenceObservable,b=e.getVisitorPriority,v=e.queuesStateUpdatesObservable,m=Ek(),y=sm.conf.communications.enabled_media_level,g=new QC({statusObservable:n,webRtcMode:m,enabledMediaLevel:y,statsClient:i,cobraObservable:r,channelObservable:o,apiStart:ZC,visitorAppPublicInterface:s,pubsub:a,visitorMetadata:c,internalVisitorStateObservable:u,routingObservable:l,volatileNotifications:p,wsProxy:f,currentStatusObservable:h,operatorPresenceObservable:d,getVisitorPriority:b,queuesStateUpdatesObservable:v});sm._getApi=t=function(e){e||(e={});var t=e.version;return t?k.contains(t,XC)?Promise.resolve(g):(nm.warn("getApi used with unsupported version ".concat(t," at ").concat(window.location.host)),Promise.reject(new Error("".concat(t," is not supported for Glia API. ")+"The supported versions are: ".concat(IA(XC))))):(console.warn("Requesting the Glia API without a version is deprecated. Provide the 'version' parameter to the sm.getApi function. Example: sm.getApi({version: 'v1'})"),nm.warn("getApi used without version at ".concat(window.location.host)),Promise.resolve(g))},k.forEach((function(e){t(e.options).then(e.resolve.bind(e))}),sm._apiHandlers),new KC({channelObservable:o,statsClient:i}).start(),ZC.next(),ZC.complete(),setTimeout((function(){sm.urlParams.showVisitorCode&&s&&(s.showVisitorCode?s.showVisitorCode():nm.info("showVisitorCode is undefined on visitorAppPublicInterface"))}))}({statusObservable:f.statusObservable,cobraObservable:f.cobraObservable,channelObservable:f.channelObservable,statsClient:n,visitorAppPublicInterface:e,pubsub:r,visitorMetadata:sm.conf.visitor_metadata,internalVisitorStateObservable:o,routingObservable:p,volatileNotifications:s,wsProxy:a,currentStatusObservable:h,operatorPresenceObservable:c,getVisitorPriority:l,queuesStateUpdatesObservable:d}),Gg({internalVisitorStateObservable:o,cobraObservable:f.cobraObservable,volatileNotifications:s,stats:n,wsProxy:a,currentStatusObservable:h,operatorPresenceObservable:c,queuesStateUpdatesObservable:d,routingObservable:p}),_m(),function(){var e=VT.get(Ex);if(e)VT.remove(Ex),Ox(document,e)}()})).catch((function(e){return nm.warn("Starting visitor app failed",{error:e})}))},setupIFrame:function(e){var t=e.getAccessToken,n=e.stats,r=e.pubsub,i=e.visitorPresenceChannel,o=e.internalVisitorStateObservable,s=e.volatileNotifications,a=e.wsProxy,c=e.bestEffortXDomainStorage,u=e.operatorPresenceObservable,l=e.xDomainUrlStorage,p=e.getVisitorPriority,f=e.routingObservable,h=new o_(e.tabId);h.start(),h.request(),sm.visitorPageNotifierSubscription={unsubscribe:a_()};var d=new u_(h,sm.conf),b=!1;return d.identityObservable().subscribe((function(e){if(b)nm.warn("Received iFrame identity after defaulting to unknown",{identity:e});else switch(b=!0,e){case d.IDENTITIES.NESTED_COBROWSABLE_IFRAME:_m(),function(e){var t=e.parentWindowMessenger,n=e.iframeContext,r=e.getAccessToken,i=e.stats;new ST(t,n.nestedCobrowsableVisitorIframeChannelUrl,r,i).boot()}({getAccessToken:t,parentWindowMessenger:h.getParentWindowMessenger(),iframeContext:h.getCurrentContext(),stats:n});break;case d.IDENTITIES.ENGAGEMENT_IFRAME:h.stop(),TR({stats:n,pubsub:r,getAccessToken:t,visitorPresenceChannel:i,internalVisitorStateObservable:o,volatileNotifications:s,wsProxy:a,operatorPresenceObservable:u,routingObservable:f});break;default:sm.conf.visitor_api.allow_embedding?(nm.info("Did not receive iFrame identity from parent, bootstrapping as top frame"),c_(),kR.setupApp({stats:n,pubsub:r,getAccessToken:t,visitorPresenceChannel:i,internalVisitorStateObservable:o,volatileNotifications:s,wsProxy:a,operatorPresenceObservable:u,bestEffortXDomainStorage:c,xDomainUrlStorage:l,getVisitorPriority:p,routingObservable:f})):nm.warn("Starting base app failed. IFrame has unknown identity. Top frame likely does not have Glia scripts installed.",{identity:e})}}))}};sm.EventEmitter=T,sm.dynamicImport=dm,sm.R=k,sm.Rx=Gv,sm.App=bm;var xR=Boolean(sm.Bootstrapper);sm.Bootstrapper={boot:function(){xR||sm.installed||(sm.installed=!0,kR.setup())}}}(sm.conf); //# sourceMappingURL=bootstrapper-ea662fcc3.js.map